RestKit Request Mapping - Post Array of objects - ios

I am trying to serialize a SyncRewardDataRequestModel in my response body. "an_id" serializes fine. However, the SyncRewardDataInputModel objects within the NSArray always serializes to a empty NSArray. I have confirmed that I am passing a correct value in my NSArray - Does anyone see what is incorrect with my mapping?
Classes:
#interface SyncRewardDataInputModel : NSObject
#property (nonatomic,copy) NSNumber *test_id;
#end
#interface SyncRewardDataRequestModel : NSObject
#property (nonatomic,strong) NSArray *syncRewardDataInputs;
#property (nonatomic,copy) NSNumber *an_id;
#end
The following is my response descriptor:
//Populate mapping
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; // objectClass == NSMutableDictionary
[requestMapping addAttributeMappingsFromDictionary:#{#"an_id": #"an_id"}];
RKObjectMapping *syncRewardDataInputsMapping = [RKObjectMapping mappingForClass:[SyncRewardDataInputModel class]];
[syncRewardDataInputsMapping addAttributeMappingsFromDictionary:#{#"test_id": #"test_id"}];
//Combine
RKRelationshipMapping *arrayRelation = [RKRelationshipMapping relationshipMappingFromKeyPath:#"syncRewardDataInputs" toKeyPath:#"downloadCardResponseDTOs" withMapping:syncRewardDataInputsMapping];
[requestMapping addPropertyMapping:arrayRelation];
//Put it in a request
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[SyncRewardDataRequestModel class] rootKeyPath:nil method:RKRequestMethodAny];
return requestDescriptor;

This line:
RKObjectMapping *syncRewardDataInputsMapping = [RKObjectMapping mappingForClass:[SyncRewardDataInputModel class]];
should be:
RKObjectMapping *syncRewardDataInputsMapping = [RKObjectMapping requestMapping];
because for a request you are always trying to map to an NSMutableDictionary so that JSON can be generated from it for transmission.
Often you will have a mapping used for the received data, linked to a response descriptor, and you can use inverseMapping on that to generate the mapping to be used for your request descriptor.

Related

RestKit RKObjectMapping of a list

I am new to RestKit and am trying to map a json object that contains an array of objects my model. I have debugged and found that the response hits my server --> json is return --> RestKit says the mapping was successful and that I have 1 object mapped... However, the errorCode field and the array of businesses (bList) are both null when I do BusinessObjectModel *response = result.array.firstObject;
in the OnSuccessBlock.
Json:
{
"bList":
[
{
"id": 1,
"name": "aName",
"owner": 1,
"category": 1,
}
{
"id": 2,
"name": "aName2",
"owner": 1,
"category": 1,
}
],
"errorCode": 0
}
Want to map this Json to this objective c object:
BussinessObjectModel Object Mapping:
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[BusinessObjectModel class]];
[responseMapping addAttributeMappingsFromDictionary:#{
#"id": #"business_id",
#"name": #"business_name",
}];
return responseMapping;
BModel:
#interface bModel : NSObject
#property (nonatomic, copy) NSNumber *errorCode;
#property (nonatomic, copy) NSMutableArray *bList;
+(RKObjectMapping *) getMapping;
#end
BModel Object Mapping:
RKObjectMapping *bMapping = [BusinessObjectModel getMapping];
RKObjectMapping *buslstMapping = [RKObjectMapping mappingForClass:[BModel class]];
[buslstMapping addAttributeMappingsFromDictionary:#{#"errorCode": #"errorCode"}];
// Define the relationship mapping
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil
toKeyPath:nil
withMapping:bussinessMapping]];
return buslstMapping;
Descriptor looks as follows:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:ResponseMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"bList" statusCodes:nil];
EDIT
I want to map the above Json to :
#interface bModel : NSObject
#property (nonatomic, copy) NSNumber *errorCode;
#property (nonatomic, copy) NSMutableArray *bList;
#end
Where bList is an array of the following object:
#interface Business : NSObject
#property (nonatomic, copy) NSNumber *id;
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSNumber *id;
#property (nonatomic, copy) NSNumber *id;
#end
I guess the question is how do I do nested relationships (what would the Response Descriptor have to be for the above relationship)?
Great to see that your using RestKit. Your first helper will be the logging that RestKit provides. Add this line of code do your AppDelegate and watch the console for errors.
// The * will send everything RestKit does to the console
// Replace the * with the module you want to check (Network/CoreData/...)
RKLogConfigureByName("RestKit/*", RKLogLevelTrace);
When looking at your JSON you want to get the objects from the keyPath "bList" on the one hand and on the other hand the error code or message when something goes wrong. RestKit provides a build in error handling to get that information out of your JSON.
Init the RKObjectMapping for the RKErrorMessage class and add a RKResponseDescriptor to your requests with the right keyPaths including the range of status codes (here using client errors). RestKit will automatically detect the error code (when sent within the header) and apply the mapping to get the content of the error message.
// Init error mapping
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:#"errorMessage"]];
// Add mapping as response descriptor
RKResponseDescriptor *errorDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:errorMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"message" // Edit the keyPath to the value of your JSON (e.g. errorCode)
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
[RKObjectManager.sharedManager addResponseDescriptor:errorDescriptor];
To get the error message when a failure occurs, you simply get the message object. When using a block to get objects, you can use the userInfo dictionary from the given NSError.
RKErrorMessage *errorMessage = [[error.userInfo objectForKey:RKObjectMapperErrorObjectsKey] firstObject];
NSLog(#"Error: %#", errorMessage);
Now you can simplify your object model a bit and concentrate on mapping the BusinessObjectModel. When mapping the object using the dictionary, you need to check of your local attributes matches the value in your JSON.
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[BusinessObjectModel class]];
[responseMapping addAttributeMappingsFromDictionary:#
{
#"value_from_remote_json": #"value_in_local_object", // e.g. #"id" : #"business_id"
...
}];
return responseMapping;
You don't need to use a RKRelationshipMapping any more. Reconfigure your objects/mappings and try again. The logging will show you the provided mapping and if the mapping operations are working. Last bit not least make sure that the mapping is in memory when using it by throwing an NSAssert error.
RKObjectMapping *bMapping = [BusinessObjectModel getMapping];
NSAssert(bMapping, #"bMapping mapping must not be nil");
Edit
To map values without a keyPath (like the "errorCode" field) additionally to the mapping of your objects, you'll need to provide an object with an according mapping. Taking the example from the documentation you'll end with something like:
// Init object
#interface RKErrorCode : NSObject
#property (nonatomic) NSNumber *errorCode;
#end
// Init mapping
RKObjectMapping *codeMapping = [RKObjectMapping mappingForClass:[RKErrorCode class]];
[codeMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:#"errorCode"]];
// Add response descriptor for request
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:codeMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"errorCode" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
Your response descriptor shouldn't have keyPath:#"bList", it should be set to nil as you don't want to drill in.
It also shouldn't use ResponseMapping based on the structure of your mappings, it should use the other mapping.
Your mapping is also wrong here:
#{
#"business_id": #"business_id",
#"business_name": #"business_name",
}];
It should be:
#{
#"id": #"business_id",
#"name": #"business_name",
}];
Because this specifies the JSON names and the core data names.
To fix your new issues, put this back:
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"bList" toKeyPath:#"bList"
And this:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:buslstMapping method:RKRequestMethodAny pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Found the solution and it looks something like this:
RKObjectMapping *bModelMapping = [RKObjectMapping mappingForClass:[business class]];
[bModelMapping addAttributeMappingsFromDictionary:#{
#"id": #"business_id",
#"name": #"business_name",
}];
RKObjectMapping *buslstMapping = [RKObjectMapping mappingForClass:[bModel class]];
[buslstMapping addAttributeMappingsFromDictionary:#{#"errorCode": #"errorCode"}];
// Define the relationship mapping
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"bList"
toKeyPath:#"bList" bModelMapping]];
return buslstMapping;
Also Change the following:
#property (nonatomic, copy) NSMutableArray *bList;
to
#property (nonatomic, retain) NSArray *bList;
This gives me a bModel object with an error code value and a bList which is an array of business which can then be cast to a business by doing the following Business *business = [bModel.blist firstObject];

RestKit : how to map an array with correct type?

Got:
#property(nonatomic, retain) NSString *user;
#property(nonatomic, retain) NSString *token;
#property(nonatomic, retain) NSArray *list;// NSNumber only please!
And:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[MyResponse class]];
[mapping addAttributeMappingsFromDictionary:#{
#"user" : #"user",
#"token" : #"token",
#"list" : #"list",
}];
And I receive Json:
{"user":"foobar","token":"azerty","list":[0,1,"2"]}
Unfortunately, list will be a mix of NSString and NSNumber. How to tell RestKit 0.2x I only want NSNumber or NSString in my NSArray?
RestKit uses KVC so surely if you just want numbers you could use the appropriate keyPath e.g. if I wanted the numbers to always be integers I could use the method integerValue which both NSNumber and NSString have:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[MyResponse class]];
[mapping addAttributeMappingsFromDictionary:#{
#"user" : #"user",
#"token" : #"token",
#"list.integerValue" : #"list",
}];
Rather than rewriting a JSON parser to do your particular task, why not just post-process 'list' and check each object with if([list[i] isKindOfClass:[NSString class]]) and convert it to an NSNumber?

RestKit 0.20 nested Object mapping (path to object tree different)

I got a problem with mapping a nested object value.
I got two objects with the following properties:
a)
class Input
#property NSString value;
#property NSString title;
b)
class Profile
#property Input myAwesomeInput;
..so a Profile contains an Input object. When I mapp the objects with RestKit (0.20) I get sth. like this:
{ myAwesomeInput_test:{"value":"xyz","title":"a title"}}
What I wanna achieve is:
{myAwesomeInput_test:"xyz"}
So I don't want to map "Input" but just the Input.value. Is that even possible?
At the moment my code looks like this:
RKObjectMapping* inputMapping = [RKObjectMapping requestMapping];
[inputMapping addAttributeMappingsFromArray:#[#"value"]];
RKRequestDescriptor *reqDescInput = [RKRequestDescriptor requestDescriptorWithMapping:inputMapping objectClass:[Input class] rootKeyPath:nil];
RKObjectMapping* searchProfile = [RKObjectMapping requestMapping];
RKRequestDescriptor *reqDescSearchProfile = [RKRequestDescriptor requestDescriptorWithMapping:searchProfile objectClass:[SearchProfile class] rootKeyPath:nil];
[searchProfile addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"myAwesomeInput" toKeyPath:#"myAwesomeInput_test" withMapping:inputMapping]];
EDIT: (solved)
Ok I solved it. Hope it's the way people should do it. You can directly address from within the dictionary.
RKObjectMapping* searchProfile = [RKObjectMapping requestMapping];
[aeSearchProfile addAttributeMappingsFromDictionary:#{
#"myAwesomeInput.value": #"myAwesomeInput_test"
}];
RKRequestDescriptor *reqDescSearchProfile = [RKRequestDescriptor requestDescriptorWithMapping:searchProfile objectClass:[SearchProfile class] rootKeyPath:nil];
Use keypaths rather than multiple mappings.
Try this:
RKObjectMapping* searchProfile = [RKObjectMapping requestMapping];
[searchProfile addAttributeMappingsFromDictionary:#{ #"myAwesomeInput.value" : #"myAwesomeInput_test" }];
RKRequestDescriptor *reqDescSearchProfile = [RKRequestDescriptor requestDescriptorWithMapping:searchProfile objectClass:[SearchProfile class] rootKeyPath:nil];

Adding two request descriptors for a given class in Restkit 0.2

I need to make two different types of POST coming from the User class.
//JSON Type A
{
"password":"12345",
"email":"test#gmail.com"
}
//JSON Type B
{
"user":{
"Password":"12345",
"Email":"sample#gmail.com"
}
}
I've tried to make two request descriptors and adding them to my object manager however I get the error
"Cannot add a request descriptor for the same object class as an
existing request descriptor."
My code
#interface User : NSObject
#property (nonatomic, retain) NSString * userID;
#property (nonatomic, retain) NSString * email;
#property (nonatomic, retain) NSString * password;
#property (nonatomic, retain) NSString * firstName;
#property (nonatomic, retain) NSString * lastName;
#end
- (void)setupUserMapping:(RKObjectManager *)objectManager {
// Setup user response mappings
RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]];
[userMapping addAttributeMappingsFromDictionary:#{
#"ID" :#"userID",
#"Email" : #"email",
#"Password" : #"password",
#"FirstName" : #"firstName",
#"LastName" : #"lastName",
}];
RKResponseDescriptor *responseDescriptorAuthenticate = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
pathPattern:#"/Authenticate"
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKResponseDescriptor *responseDescriptorRegister = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
pathPattern:#"/Register"
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptorRegister];
[objectManager addResponseDescriptor:responseDescriptorAuthenticate];
// Setup user request mappings
RKObjectMapping* userRequestMappingForRegister = [RKObjectMapping requestMapping];
[userRequestMappingForRegister addAttributeMappingsFromDictionary:#{
#"email" : #"Email",
#"password" : #"Password",
#"firstName" : #"FirstName",
#"lastName" : #"LastName",
}];
RKRequestDescriptor *requestDescriptorForRegister = [RKRequestDescriptor requestDescriptorWithMapping:userRequestMappingForRegister objectClass:[User class] rootKeyPath:#"user"];
RKObjectMapping* userRequestMappingForAuthenticate = [RKObjectMapping requestMapping];
[userRequestMappingForAuthenticate addAttributeMappingsFromDictionary:#{
#"userID" :#"ID",
#"email" : #"email",
#"password": #"password"
}];
RKRequestDescriptor *requestDescriptorForAuthenticate = [RKRequestDescriptor requestDescriptorWithMapping:userRequestMappingForAuthenticate objectClass:[User class] rootKeyPath:nil];
[objectManager addRequestDescriptor:requestDescriptorForRegister];
[objectManager addRequestDescriptor:requestDescriptorForAuthenticate];
}
Does anyone know how I can solve this problem without creating a separate class for these requests?
Any help is appreciated.
Thanks.
You can use a dynamic mapping to switch the serialization behaviors. If this is a common enough issue, we could conceivably add path matching to the request descriptor. I just have not had a ton of requests for such a feature.
There is an example of how to use the dynamic mapping with a request in the unit tests: https://github.com/RestKit/RestKit/blob/master/Tests/Logic/ObjectMapping/RKObjectParameterizationTest.m#L495-L534
For multiple request descriptors, I declared a new model class with the same data members as the earlier one, and then referenced it while adding the request descriptor instead of the earlier one as follow.
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[CMAGoogleUserDataModel class]];
Here the newly created class was "CMAGoogleUserDataModel"
Noted: I am not sure whether it is the optimised one or not, but it did solve my use case.

How receive Integer value in RestKit 0.20?

I've rest Object as:
#interface VFEQuestionnaireRest : NSObject
#property(copy ,nonatomic) NSNumber *iid;
#property(copy, nonatomic)NSString *namePoll;
#property(copy, nonatomic)NSSet *questions;
#end
and coming JSON as:
{"questionnaire":[
{"id":4,"namePoll":"questionario4","questions":
{"id":13,"idQuestionnaire":4,"nameQuestion":"costo?",
"questionType":{"id":2,"nameType":"WHOLE"}}}]}
The value "iid" is always "0", and namePoll have its correct value.
How can mapping int value from JSON to NSNumber objC?
-
RKObjectMapping *questionnaireMapping = [RKObjectMapping mappingForClass:[VFEQuestionnaireRest class]];
[questionnaireMapping addAttributeMappingsFromDictionary:
#{#"iid":#"id",
#"namePoll":#"namePoll"
}];
[questionnaireMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"questions" toKeyPath:#"questions" withMapping:questionMapping]];
I believe your mapping is incorrect. It should be source -> destination and not the other way around:
RKObjectMapping *questionnaireMapping = [RKObjectMapping mappingForClass:[VFEQuestionnaireRest class]];
[questionnaireMapping addAttributeMappingsFromDictionary:
#{ #"id":#"iid",
#"namePoll":#"namePoll" }];
Restkit performs int -> NSNumber conversion automatically.

Resources