POST 到服务器时嵌套对象的 RestKit 错误
Posted
技术标签:
【中文标题】POST 到服务器时嵌套对象的 RestKit 错误【英文标题】:RestKit error for a nested object while POSTing to server 【发布时间】:2015-12-10 13:59:54 【问题描述】:我有一个服务要发送以下类型的请求
"ClientDetails":"ChauffeurId":0,"FirstName":"String","LastName":"String","Email":"String","Password":"String","PhoneNumber":"String","Thumbnail":"AA==","PayKey":"String","DeviceKey":"String","Token":"String"
我正在使用以下代码使用所示的 RestKit 映射发送此请求,问题是我收到“JSON 写入(客户端)中的类型无效”错误,无法弄清楚错误是什么。
RKObjectMapping *requestMapping = [RKObjectMapping mappingForClass:[Client class]];
[requestMapping addAttributeMappingsFromDictionary:@ @"FirstName": @"FirstName", @"LastName": @"LastName",@"Email":@"Email",@"PhoneNumber":@"PhoneNumber",@"Token":@"PayKey",@"Password":@"Password",@"ChauffeurId":@"ChauffeurId",@"Image":@"Thumbnail",@"DeviceToken":@"DeviceKey" ];
RKObjectMapping *tokenMapping = [RKObjectMapping requestMapping];
[tokenMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"token" toKeyPath:@"Token"]];
[tokenMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"client"
toKeyPath:@"ClientDetails"
withMapping:requestMapping]];
RKRequestDescriptor *tokenReqDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:tokenMapping
objectClass:[RegClientRequest class]
rootKeyPath:nil method:RKRequestMethodPOST];
// Register our descriptors with a manager
RKObjectManager *manager = [RKObjectManager sharedManager];
[manager addRequestDescriptor:tokenReqDescriptor];
Client *client = [Client new];
NewUser *user = [NewUser sharedNewUser];
client.FirstName = user.strFname;
client.LastName = user.strLname;
client.Password = user.strPwd;
client.PhoneNumber = user.strNum;
client.Email = user.strEmail;
client.Token = user.strToken;
client.DeviceToken = user.strDeviceToken;
RegClientRequest *regClientRequest = [RegClientRequest new];
regClientRequest.token = [ServiceUrls token];
regClientRequest.client = client;
[manager postObject:regClientRequest path:[ServiceUrls registerUser] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result)
【问题讨论】:
您定义了requestMapping
,但实际上并没有使用它...
@Wain 不确定我应该把它放在哪里,根据需要的 json,是的,这是一个错误,谢谢指出,你能指导吗?
在tokenMapping
中,您应该为客户端使用关系,而不是尝试直接映射它。
@wain 试过了会再试告诉你
@wain 还是同样的错误,更新了代码,看看现在是否正确
【参考方案1】:
问题是您正在创建一个特定于类的映射,您应该在其中使用[RKObjectMapping requestMapping
或采用inverseMapping
。
这意味着此时您正在将客户端映射到客户端并尝试将生成的客户端放入 JSON(而不是将客户端映射到字典)。
【讨论】:
以上是关于POST 到服务器时嵌套对象的 RestKit 错误的主要内容,如果未能解决你的问题,请参考以下文章
Restkit:从核心数据获取到服务器的 POST 对象数组
如何使用 RestKit 将嵌套的 JSON 对象存储到核心数据中