我有两个JSON,看起来像:
{
"749": {
"email": "myMail@me.com",
"firstname": "Mr",
"lastname": "Smith"
}
}
和
[
{
"entity_id": "1",
"city": "myCity",
"country_id": "UA",
"region": null,
"postcode": "001",
"telephone": "+38000000001",
"fax": null,
"street": [
"myStrit ",
"12"
],
"is_default_billing": 1,
"is_default_shipping": 0
},
{
"entity_id": "2",
"city": "myCity",
"country_id": "UA",
"region": null,
"postcode": "001",
"telephone": "+3800000002",
"fax": null,
"street": [
"myStrit2",
"33"
],
"is_default_billing": 0,
"is_default_shipping": 1
}
]
获取第一个JSON的路径为mySite/customers
,第二个JSON的路径为mySite/customers/:userId/addresses
。
其中userId
是来自第一个JSON的未命名属性(在我的示例中为749)。
我是RestKit的新手,我无法弄明白,如何通过一个请求来映射...
PS:我从Magento rest api获得了这些JSON。
答案 0 :(得分:0)
你没有说明你要映射的内容,但是。
对于第一个JSON,您需要在映射上使用addAttributeMappingFromKeyOfRepresentationToAttribute
来提取749
值并同时将其用作键。
对于第二个JSON,似乎没有与第一个JSON的任何连接,因此您需要尝试映射并返回特定问题。有关指导,请参阅this page。
答案 1 :(得分:0)
RestKit希望每个对象都由一个可由mapper处理的字典描述。但是,您的服务不会返回一个对象数组,而是一个字典字典,RestKit无法将其正确解释为可以单独映射的对象集合。当然,如果您的服务可以返回一组字典,问题就会消失。
幸运的是,有一种方法可以在调用映射器之前将您收到的词典字典转换为字典数组。这可以通过-[RKObjectRequestOperation setWillMapDeserializedResponseBlock:]
设置转换块来实现。
该块接收初始解析的结果(这里是字典词典),您可以通过调用-[NSDictionary allValues]
轻松将其转换为字典数组:
RKManagedObjectStore *managedObjectStore = ...;
RKResponseDescriptor *responseDescriptor = ...;
NSURLRequest *request = ...;
RKManagedObjectRequestOperation *managedObjectRequestOperation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
managedObjectRequestOperation.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext;
[managedObjectRequestOperation setWillMapDeserializedResponseBlock:^id(id deserializedResponseBody) {
return [deserializedResponseBody allValues];
}];
[[NSOperationQueue currentQueue] addOperation:managedObjectRequestOperation];