Mapping a JSON response to an object using RestKit and Objective-C - objective-c

I am relatively new to Objective-C and am attempting to use RestKit to receive a JSON response from a web service. I have successfully received the data back to my application, which looks like this viewing the response:
{id:"1","Translation":"Test"}
I would like to map this translation to my "Translation" object in my application, but have tried a few different ways but am not sure how to achieve this.
So my questions are:
How can I map this response to my Translation object
Am I doing this correctly, creating a method to complete this call outwit my view controller?
My Translation Object
#implementation Translation
#synthesize identifier = _identifier;
#synthesize translation = _translation;
- (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
#"id", #"identifier",
#"translation", #"translation",
nil];
}
#end
My Translate Method
- (NSString *)performTranslation:(NSString *)translation
{
NSString *data = [[NSString alloc] initWithFormat:#"{\"SourceId\": \"%#\",\"RegionTag\": \"%#\",\"InputString\": \"%#\"}", #"1", #"Glasgow", translation];
NSString *post = data;
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:#"http://my.url.com/Translation/Translate"]];
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = post;
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:#"application/json", #"Content-Type", #"application/json", #"Accept", nil];
[MyRequest send];
RKResponse *Response = [MyRequest sendSynchronously];
return Response.bodyAsString; <--- looking to map this to translation object here
}

The snippet of your code seems a bit outdated. I strongly recommend reading the newest Object Mapping guide in order to leverage RestKit into it's fullest potential - especially the part Mapping without KVC.
Edit:
In order to post an object with RestKit and receive back an answer, we define a TranslationRequest class that will hold our request & Translation to hold our response.
Firstly, we set up our RKObjectManager and mappings (i usually do this in my AppDelegate):
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kOurBaseUrl];
[manager setSerializationMIMEType:RKMIMETypeJSON];
//this is a singleton, but we keep the manager variable to avoid using [RKObjectManager sharedManager] all the time
//Here we define a mapping for the request. Note: We define it as a mapping from JSON to entity and use inverseMapping selector later.
RKObjectMapping *translationRequestMapping = [RKObjectMapping mappingForClass:[TranslationRequest class]];
[translationRequestMapping mapKeyPath:#"RegionTag" toAttribute:#"regionTag"];
...
[[manager mappingProvider] setSerializationMapping:[translationRequestMapping inverseMapping] forClass:[TranslationRequest class]];
//now we define the mapping for our response object
RKObjectMapping *translationMapping = [RKObjectMapping mappingForClass:[Translation class]];
[translationMapping mapKeyPath:#"id" toAttribute:#"identifier"];
[translationMapping mapKeyPath:#"Translation" toAttribute:#"translation"];
[[manager mappingProvider] addObjectMapping:mapping];
//finally, we route our TranslationRequest class to a given endpoint
[[manager router] routeClass:[TranslationRequest class] toResourcePath:kMyPostEndpoint];
This should be enough of the necessary setup. We can call our backend anywhere in the code (e.g. in any controller) like this:
//we create new TranslationRequest
TranslationRequest *request = [[TranslationRequest alloc] init];
[request setRegionTag:#"Hello"];
....
//then we fetch the desired mapping to map our response with
RKObjectMapping *responseMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:class]
//and just call it. Be sure to let 'self' implement the required RKObjectManagerDelegate protocol
[[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self];]
Try this approach and let me know if you need any assistance.. I was not able to test it fully as i don't have any suitable backend that will return the responses, but judging from the RestKit log this should work.

You need to pass the returned JSON string into a JSON parser. I use SBJSON. You can then use the resulting dictionary to populate the properties of your object.
RestKit seems to have native objects that encapsulate four different JSON parsers. However, I'd advise caution because they seem to assume that the top level parsed object will always be a dictionary.
As another aside, the example in your question is not valid JSON. It should look like this:
{"id":"1","Translation":"Test"}

Related

RestKit - Object Mapping functions not found

I'm naïvely trying to follow the guidelines for mapping one of my CoreData classes with RestKit 0.20
#import <RestKit/RestKit.h>
...
RKObjectMapping *mymap =
[RKObjectMapping mappingForClass: NSClassFromString(#"MY_CLASS")];
[mymap mapAttributes:#"field1", #"field2", nil];
But
No visible #interface for 'RKObjectMapping' declares the selector 'mapAttribute'
If I type [mymap map, I see only these 2 functions in the completion list
id mappingForDestinationKeyPath:(NSString *)
id mappingForSourceKeyPath:(NSString *)
What am I doing wrong ?
An other example, when I try to use the shared RKObjectManager
[[RKObjectManager sharedManager].mappingProvider setMapping:map forKeyPath:#"/"];
It can't find the member mappingProvider
I think this is a problem with the wiki page, mapAttributes: is not found in the RKObjectMapping docs (http://restkit.org/api/master/Classes/RKObjectMapping.html). I think the wiki page is out of date, use this one instead: https://github.com/RestKit/RestKit/wiki/Object-Mapping
You should use the addAttributeMappingsFromDictionary method instead:
[mymapp addAttributeMappingsFromDictionary:#{#"field1" : #"field1"}];
Also mappingProvider is from pre-0.20 rest kit, and has been replaced with response descriptors (objects which are used to determine which mapping to use for a response)
RKResponseDescriptor *descriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:nil keyPath:#"key_path" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:descriptor];
Use mapping like this:
RKManagedObjectMapping * mymap = [RKManagedObjectMapping mappingForClass:[MY_CLASS class] inManagedObjectStore:self.objectStore];
mymap.setDefaultValueForMissingAttributes = YES;
mymap.primaryKeyAttribute = #"MY_CLASS_ID";
mymap.rootKeyPath = #"ROOT_PATH_OF_SERVICE";
[mymap mapKeyPathsToAttributes:
#"WEB_SERVICE_ATTRIBUTE1", #"DATA_MODAL_ATTRIBUTE1",
#"WEB_SERVICE_ATTRIBUTE2", #"DATA_MODAL_ATTRIBUTE2",
#"WEB_SERVICE_ATTRIBUTE3", #"DATA_MODAL_ATTRIBUTE3",
nil];

RestKit: how to map URL param to object attribute

I've got REST service method like this one
/GetOfficeDocument?officeId=259
which returns an array of documents. Document in the app is a NSManagedObject object that has relationship to an office. How can I map officeId param to office relationship of my Document?
I know I should override objectLoader:willMapData:, but I don't know what exactly should I do inside of this method. The documentation is useless.
UPD. The response of the server looks like this:
[{"AddedDate":"\/Date(1261484400000+0400)\/","Title":"Some text","Uri":"\/Document\/News\/851"}]
As you see, officeId is not contained in response, only in URL. I can extract it in objectLoader:willMapData: using
[[[loader URL] queryParameters] objectForKey:#"officeId"]
but where should I put it next? Mappable data parameter is a mutable array, what should I place there? No idea.
You could try to inject the OfficeId value in each document item returned in the response like so:
- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout __autoreleasing id *)mappableData
{
NSString *officeId = [[[loader URL] queryParameters] objectForKey:#"officeId"];
NSMutableArray *newMappableData = [[NSMutableArray alloc] initWithCapacity:[*mappableData count]];
for (NSDictionary *documentDict in *mappableData)
{
NSMutableDictionary = newDocumentDict = [documentDict mutableCopy];
[newDocumentDict setObject:officeId forKey:#"OfficeId"];
[newMappableData addObject:newDocumentDict];
}
*mappableData = newMappableData;
}
And use something similar to the following in your Document mapping:
[documentMapping mapAttributes:#"AddedDate", #"Title", #"Uri", #"OfficeId", nil];
[documentMapping mapKeyPath:#"" toRelationship:#"office" withMapping:officeMapping];
[documentMapping connectRelationship:#"office" withObjectForPrimaryKeyAttribute:#"OfficeId"];
I usually add the RKObjectMapping to the managedObject class
Add this to your Document.h
+ (RKObjectMapping *)objectMapping;
Add this method to your Document.m
+ (RKObjectMapping *)objectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
mapping.primaryKeyAttribute = #"word";
[mapping mapKeyPath:#"word" toAttribute:#"word"];
[mapping mapKeyPath:#"min_lesson" toAttribute:#"minLesson"];
}
Off course you should change the key paths to your Document object properties. each pair is the name of the key on the server responds and it's corresponded keyPath on your managedObject.
Then when you initialize the objectManager you can set the mapping for each managedObject you have.
RKManagedObjectStore *store = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self];
objectManager.objectStore = store;
//set the mapping object from your Document class
[objectManager.mappingProvider setMapping:[SRLetter objectMapping] forKeyPath:#"Document"];
YOu can find a great tutorial here - RestKit tutorial. In the middle of the article you will find data about mapping.

iOS: RestKit loadObject & send params

using loadObjectAtResourcePath on GET method, doesn't include my parameters on the requests.
for example, if I send:
[RKObjectManager objectManagerWithBaseURL:#"http://something/ws"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:#"/res" delegate:self block:^(RKObjectLoader *loader) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"val", #"param1",
nil];
loader.params = [RKParams paramsWithDictionary:dict];
}];
the final url request doesn't include the "?param1=val" part - why?
Update Months Later
The real answer is that loader.params creates the HTTP BODY, hence it works for POST, PUT, DELETE etc but not for GET where the params are appended to the URL.
Hence, the answer below still works if you're facing the same issue for GET, but if you're sending out GET requests, it's mostly using methods that attach the params to the query string.
To summarize the differences between the two.
Sending params in the HTTP Body(i.e. POST, UPDATE, DELETE)
// Convert a NS Dictionary into Params
RKParams *params = [RKParams paramsWithDictionary:optionValues];
// I use sendObject to skip the router. Otherwise it's normally postObject
[[RKObjectManager sharedManager] sendObject:yourObject toResourcePath: yourResourcePath usingBlock:^(RKObjectLoader *loader) {
loader.method = RKRequestMethodPOST;
loader.delegate = delegate;
loader.params = params; // This sets params in the POST body and discards your yourObject mapping
} ];
Caveat Emptor (for above)
Setting params in the block destroys any mapping that you might have set in yourObject, kind of defeats the purpose of using object mapping. There's a fix here by Sebastian loader.params - Extra params if you really want to use this method to append extra parameters to your Post not in the object.
Sending in params as Query String (i.e. GET)
// Make a NS dictionary and use stringByAppendingQueryParameters
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
#"limit",#"20",
#"location",#"latitude,longitude",
nil];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[#"/api/v1/shops.json" stringByAppendingQueryParameters:shopParams] delegate:objectDelegate];
The rest of the answer is just for reference, I'm a hoarder.
Old Answer
I'm using RestKit for my project and facing the same issue.
I think RKParams is mainly used to do POST requests. I cannot fully decipher your code because 1) I don't know loader's declaration? 2) RKParams is not to be used with Object Manager?
I did this.
Loader Method in App Delegate
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:#"limit",#"30", nil];
[[RKClient sharedClient] get:#"/api/v1/shops.json" queryParams:shopParams delegate:self];
Delegate
- (void)requestDidStartLoad:(RKRequest *)request {
NSLog(#"RK Request description: %#",[request description]);
}
Output:
RK Request description: <RKRequest: 0x7993db0> and rails log say {"limit"=>"30"}.
From the autocomplete in Xcode, you can see the get request didn't even use RKParams. Just a NSDict. The POST requests uses it.
My goal is to attach a query string, i.e. ?location=singapore&etcetc to my API methods in Rails. For this, RK comes with a NSString addon called appendQueryParams RK docs link that you can use to append query params.
If your goal is POST images etc, you can follow the above line of thought of using RKClient.
Update:
If you just want to append parameters to Object Manager
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
#"limit",#"20",
#"location",#"latitude,longitude",
nil];
This is outdated and marked for deprecation.
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[#"/api/v1/shops.json" appendQueryParams:shopParams] delegate:self];
Use this instead:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[#"/api/v1/shops.json stringByAppendingQueryParameters:shopParams] delegate:yourLoaderDelegate];
Rails Log: {"location"=>"latitude,longitude", "limit"=>"20"}
Hope in my answer I didn't make any wrong statements.
Refer to this question RestKit GET query parameters.

loadObjectsAtResourcePath (RestKit)

I have a method like this.
- (void)loadData {
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:#"http://localhost:8080/activiti-rest/service"];
[manager loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectClass:[Data class] delegate:self];
}
I get an error that says:
instance method '-loadObjectsAtResourcePath:objectClass:delegate' not found('return types default to 'id' ').
Can someone please help me how to call loadObjectsAtResourcePath function?
Maybe you want to define the mapping manually. Then just do something like this:
RKObjectMapping *mapping = [[[RKObjectManager sharedManager] mappingProvider] objectMappingForClass:[Data class]];
RKObjectLoader *loader = [[RKObjectManager sharedManager] loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectMapping:mapping delegate:self];
Don't forget to set base resource path to your RKObjectManager singleton.
I had to use the prototype that has objectMapping in it because i was trying to map the response to my own mapping called Data.
So i created an RKObjectMapping object ,configured to my own mapping class and then used this function.
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Data class]];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:#"http://localhost:8080/activiti-rest/service"];
[manager loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectMapping:mapping delegate:self] ;
It worked!
Without knowing RestKit This sounds like a simple header problem. look at the header where "RKObjectManager" is defined. (Cmd click it in XCode to make sure it's available in your project.) Double check the method definition and make sure you're calling it correctly. Always use auto-complete to invoke methods.
Is your object/class implementing the in the interface?

RestKit: How does one post an array of objects?

Question summary:
Consider a class SyncObject that is KVC-compliant with properties such as: time, someValue, lastChange, uuid.
Consider an NSArray containing exclusively instances of SyncObject.
I need to submit the array to the server as a JSON array.
How would one submit this array to the server using HTTP POST using RestKit?
Example array:
[
{
"time": "14:45 10/21/2011",
"someValue": "15",
"lastChange": "14:45 10/21/2011",
"uuid": "0b07c510-f4c8-11e0-be50-0800200c9a66"
},
{
"time": "14:50 10/21/2011",
"someValue": "62",
"lastChange": "14:51 10/21/2011",
"uuid": "1a6d4480-f4c8-11e0-be50-0800200c9a66"
}
]
Details
I have an array of objects that I need to the server as JSON. It seems to me that RestKit is the easiest way to do this: I'm trying to avoid converting objects into a set of NSDictionary objects, and then using some JSON encoder to get JSON which I can POST to the server.
So, having created the array, and having set up the mapping for the class of objects stored in the array, I naturally try to POST to the server.
RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:#"http://localhost/someweb/api/"];
mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
mgr.client.username = #"username";
mgr.client.password = #"password";
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping mapKeyPath: #"time" toAttribute:#"time" ];
[mapping mapKeyPath: #"someValue" toAttribute:#"someValue" ];
[mapping mapKeyPath: #"lastChange" toAttribute:#"lastChange" ];
[mapping mapKeyPath: #"uuid" toAttribute:#"uuid" ];
RKObjectMapping* mappingForSerialization = [mapping inverseMapping];
[mgr.mappingProvider setSerializationMapping:mappingForSerialization
forClass:[NSManagedObject class]];
[mgr.router routeClass:[NSManagedObject class] toResourcePath:#"/sync" forMethod:RKRequestMethodPOST];
[mgr postObject:array delegate:nil/*self*/];
However, this is what I get out:
2011-10-11 14:57:51.769 AppConnect[1974:6e0b] *** Terminating app due to uncaught exception '(null)', reason: 'Unable to find a routable path for object of type '__NSArrayI' for HTTP Method 'POST''
Apparently, RestKit does not know how to handle NSArrays.
How does one post an array of objects using RestKit?
I've tried something different: I replaced the last line with a manual send through RKObjectLoader.
//[mgr postObject:[NSMutableDictionary dictionaryWithObject:array forKey:#"data"] delegate:nil/*self*/];
NSString* syncPath = #"/sync";
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSDictionary dictionaryWithObject:array
forKey:#"MyData"];
[objectLoader send];
Unfortunately, this does not apply mapping of any sort, and instead transmits an array of objects' descriptions. Setting serializationMIMEType also does not affect the structure of transmitted contents, and params are always transmitted as application/x-www-form-urlencoded.
I also tried assigning serialization mapping and passing the object as targetObject and sourceObject (this seems to be what RestKit does internally in -[RKObjectManager postObject:delegate:]).
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSMutableDictionary dictionaryWithObject:array
forKey:#"MyData"];
objectLoader.serializationMapping = mapping;
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.sourceObject = objectLoader.params;
objectLoader.targetObject = objectLoader.params;
[objectLoader send];
Unfortunately, no mapping occurs this way:
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.network:RKObjectLoader.m:290 POST or PUT request for source object {
MyData = (
"<NSManagedObject: 0x5935430> (entity: SomeRecord; id: 0x5934da0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p1> ; data: <fault>)",
"<NSManagedObject: 0x5935730> (entity: SomeRecord; id: 0x5934db0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p2> ; data: <fault>)"
);
}, serializing to MIME Type application/json for transport...
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:428 Starting mapping operation...
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'time'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'someValue'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'lastChange'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'uuid'
2011-10-12 12:36:48.145 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:448 Mapping operation did not find any mappable content
2011-10-12 12:36:48.146 MyProject[5119:207] T restkit.network:RKRequest.m:211 Prepared POST URLRequest '<NSMutableURLRequest http://someurl/api/sync?request=provide_key>'. HTTP Headers: {
Accept = "application/json";
"Content-Length" = 0;
}. HTTP Body: .
The restkit does not fund routable path for NSArray, because you defined your routing for NSManagedObject class. You probably want to create a custom class, say MySyncEntity that holds the ivars you define in your mapping. Then, you create your mapping like this:
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
....
[myManager setSerializationMIMEType:RKMIMETypeJSON];
[[myManager router] routeClass:[MySyncEntity class] toResourcePath:#"/sync"];
then you should be able to post your object to the API backend as JSON object.
Further clarification:
In this case, we want to post an array of NSManagedObject instances into a JSON based API. To do that we need to create a sync entity, that holds the objects in an array:
#interface MySyncEntity : NSObject {}
#property (nonatomic, retain) NSArray* mySyncArray;
...
#end
The mySyncArray will hold the payload we'd like to submit to the rest backend. Then, we create appropriate mapping for both NSManagedObject that will be sent in mySyncArray and the MySyncEntity entity itself.
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kBaseUrl];
...
RKObjectMapping *mngObjMapping = [RKObjectMapping mappingForClass:[NSManagedObject class]];
[mngObjMapping mapKeyPath: #"time" toAttribute:#"time"];
[mngObjMapping mapKeyPath: #"recordLevel" toAttribute:#"recordLevel"];
.... //map as many properties as you wish
[[manager mappingProvider] setSerializationMapping:[mngObjMapping inverseMapping]
forClass:[NSManagedObject class]];
//now, we create mapping for the MySyncEntity
RKObjectMapping *syncEntityMapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
[[manager mappingProvider] setSerializationMapping:[syncEntityMapping inverseMapping]
forClass:[MySyncEntity class]];
Now with the mappings defined we can post the object to the server
[manager postObject:mySyncInstance delegate:nil];
The contents of mySyncInstance array will be mapped according to mngObjMapping and sent to defined rest endpoint.
As a further clarification, I'd like to point out that in mja's answer the key thing is
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
This says "the mySyncArray keypath is an array which contains objects that should be mapped according to mngObjMapping".