Reputation: 189
I have two JSONs, which are looking like:
{
"749": {
"email": "[email protected]",
"firstname": "Mr",
"lastname": "Smith"
}
}
and
[
{
"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
}
]
Path for getting first JSON is mySite/customers
, and for the second is mySite/customers/:userId/addresses
.
where userId
is unnamed attribute from first JSON (749 in my example).
I am new in RestKit and I can't really figure out, how to map it by one request...
PS: I get these JSONs from Magento rest api.
Upvotes: 0
Views: 98
Reputation: 561
RestKit expects each object to be described by a dictionary which can be processed by the mapper. Your service does not return an array of objects, though, rather a dictionary of dictionaries, which RestKit cannot correctly interpret as a collection of objects it can map individually. Of course, the problem would disappear if your service could return an array of dictionaries instead.
Fortunately, there is a way to transform the dictionary of dictionaries you receive into an array of dictionaries right before the mapper is called. This is achieved by setting a conversion block via -[RKObjectRequestOperation setWillMapDeserializedResponseBlock:]
.
The block receives the result of the initial parsing (here the dictionary of dictionaries), which you can easily turn into an array of dictionaries by calling -[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];
Upvotes: 0
Reputation: 119041
You say nothing about what you're trying to map into, but.
For the first JSON, you need to use addAttributeMappingFromKeyOfRepresentationToAttribute
on the mapping to extract the 749
value and use it as a key at the same time.
For the second JSON there doesn't appear to be any connection to the first so you need to try mapping that and come back with specific issues. See this page for guidance.
Upvotes: 0