I have a mapped object which have this property:
#interface SynchObj : NSObject
#property (nonatomic, copy) NSDictionary *fields;
#end
mapped as
mappingDict = #{ #"fields" :#"fields",};
responseMapping = [RKObjectMapping mappingForClass:[SynchObj class]];
[responseMapping addAttributeMappingsFromDictionary:mappingDict];
But when the server send a dictionary like this
{
name:null
surname:null
}
the mapping produces a dictionary with these values:
name : "<null>"
surname : "<null>"
I would like to have "" instead of "". Is it possible?
You should be able to use KVC validation which RestKit supports to verify / edit the value before it is set. If you implement validateValue:forKey:error: on your destination class (SynchObj) you can verify and edit the value being set for any key (you would need to iterate the keys and values of the dictionary).
Related
Context:
// JSON
"Name_Field" : {
"param_1":"value_1",
"param_2":"value_2"
}
// Class
class Field {
name
param1
param2
}
// Mapping Functionality
[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:#"name"];
[mapping addAttributeMappingsFromDictionary:#{
#"(name).param_1":#"param1",
#"(name).param_2":#"param2"
}];
Problem:
I am currently working with the above JSON / Class / Mapping code. I have been using this for a while and everything has been working as expected.
Today I have run into the scenario where the key in the JSON contains parenthesis and causes the mapping to fail. Is there a way I can get this to work?
Thanks!
Example:
"Name (haha this will break)" : {
"param_1":"value_1",
"param_2":"value_2"
}
I think RestKit gets confused because it does not know which parenthesis to use while mapping. So my guess would be to replace them with braces:
[mapping addAttributeMappingsFromDictionary:#{
#"{name}.param_1":#"param1",
#"{name}.param_2":#"param2"
}];
Let me know if this worked.
Solution:
Update the RKStringByReplacingUnderscoresWithBraces method in RKPropertyMapping to not replace the parenthesis with braces and then be sure to use braces in your attribute mappings.
// RKPropertyMapping
static NSString *RKStringByReplacingUnderscoresWithBraces(NSString *string)
{
return string;
//return [[string stringByReplacingOccurrencesOfString:#"(" withString:#"{"] stringByReplacingOccurrencesOfString:#")" withString:#"}"];
}
// Attribute Mappings
[mapping addAttributeMappingsFromDictionary:#{
#"{name}.param_1":#"param1",
#"{name}.param_2":#"param2"
}];
Explanation:
https://github.com/RestKit/RestKit/wiki/Object-mapping#handling-dynamic-nesting-attributes
In the above RestKit documentation when you are attempting to map a key to property you are instructed to use addAttributeMappingFromKeyOfRepresentationToAttribute and then map the nested keys using parentheses to denote your property followed by a '.' and your nested key.
In RestKit after it performs the map from the addAttributeMappingFromKeyOfRepresentationToAttribute attribute mapping it loops through all of your defined attribute mappings to replace your placeholder with the actual value from the key so the additional mapping operations can take place. During this process it creates a new RKPropertyMapping object and sets it's sourceKeyPath and destinationKeyPath. The property setters for these properties take the value and replace the parenthesis with braces and then RestKit does not find the incorrect mappings for the value with braces.
Example Context:
// JSON
{ "blake": {
"email": "blake#restkit.org",
"favorite_animal": "Monkey"
}
}
// Class
#interface User : NSObject
#property (nonatomic, copy) NSString* email
#property (nonatomic, copy) NSString* username;
#property (nonatomic, copy) NSString* favoriteAnimal;
#end
// Mapping
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class] ];
[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:#"username"];
[mapping addAttributeMappingsFromDictionary:#{
#"(username).email": #"email",
#"(username).favorite_animal": #"favoriteAnimal"
}];
Example Mapping:
// Resulting Attribute Mappings
#"{username}.email": #"email",
#"{username}.favorite_animal": #"favoriteAnimal"
// 1. The attribute mapping has been performed for 'blake' > 'username'
// 2. RestKit now loops through your attribute mappings to replace '{username}' with 'blake' so your further nested attribute mappings can take place
// 3. Example: #"{username}.email": #"email"
sourceKeyPath = #"{username}.email"
destinationKeyPath = #"email"
* replaces values *
sourceKeyPath = #"blake.email"
destinationKeyPath = #"email"
* creates a new RKPropertyMapping object *
RKPropertyMapping
- sourceKeyPath = #"blake.email"
- destinationKeyPath = #"email"
Example Mapping With Parenthesis:
// JSON
{ "blake (a.k.a GOAT)": {
"email": "blake#restkit.org",
"favorite_animal": "Monkey"
}
}
// Resulting Attribute Mappings
#"{username}.email": #"email",
#"{username}.favorite_animal": #"favoriteAnimal"
// 1. The attribute mapping has been performed for 'blake (a.k.a GOAT)' > 'username'
// 2. RestKit now loops through your attribute mappings to replace '{username}' with 'blake (a.k.a GOAT)' so your further nested attribute mappings can take place
// 3. Example: #"{username}.email": #"email"
sourceKeyPath = #"{username}.email"
destinationKeyPath = #"email"
* replaces values *
sourceKeyPath = #"blake (a.k.a GOAT).email"
destinationKeyPath = #"email"
* creates a new RKPropertyMapping object *
RKPropertyMapping
- sourceKeyPath = #"blake {a.k.a GOAT}.email" // DOES NOT MATCH
- destinationKeyPath = #"email"
I am using Restkit 0.26.0 to map JSON with multiple layers and this key path causes trouble:
productColorImages: [
{
id: 10,
productId: "232",
color: "green",
url: "exampleURL.com"
},
{
id: 11,
productId: "232",
color: "red",
url: "exampleURL.com"
},
{
id: 12,
productId: "232",
color: "blue",
url: "exampleURL.com"
}
],
My mapping
RKObjectMapping *transferProductColorImageMapping = [RKObjectMapping mappingForClass:[TransferProductColorImage class]];
[transferProductColorImageMapping addAttributeMappingsFromDictionary:#{ #"identifier" : #"id",
#"URL" : #"URL",
#"productId" : #"productId",
#"color" : #"color"
[getProductPageMapping addRelationshipMappingWithSourceKeyPath:#"productColorImages" mapping:transferProductColorImageMapping];
The destination class
#interface TransferProductColorImage : NSObject
#property (nonatomic) NSNumber * identifier; // Mapps to id ;int 64
#property (nonatomic) NSString * URL;
#property (nonatomic) NSString * productId;
#property (nonatomic) NSString * color;
The problem is that the resulting Object is of the right class but the properties are not filled.
I searched in the logs and found this:
2016-05-30 17:42:24.007 thebrandsapp[20697:7047455] T restkit.object_mapping:RKMappingOperation.m:1173 Performing mapping operation: <RKMappingOperation 0x7f9e3b9c11e0> for 'TransferProductColorImage' object. Mapping values from object {
color = green;
id = 10;
productId = 232;
url = "exampleURL.com";
} to object <TransferProductColorImage: 0x7f9e3b846d60> with object mapping (null)
On the Model Object the productColorImages is a NSArray:
#property (nonatomic) NSArray <TransferProductColorImage *> * productColorImages;
This is odd because. How does Restkit know what mapping to use if the mapping is null. Is there any reason why the object mapping could be set to null?
Update: I found that the identifier and the color property were mapped correctly it is, the identifier and the url are not mapped correctly.
I changed the URL property to be lowercase: "url" and mapped it exactly like I did before and it worked. It seems like the the all-caps property name threw RestKit of.
I swooped identifier and id, now they map correctly as well.
I am using JSONModel in my application. Is it possible to prepare category with JSONValueTransformer that will transform nil/null NSString to empty string (#""). So far when property in json response is null, my property in object becomes #"".
Because the whole API is not very well (it's external) I would like to avoid overriding initWithDictionary in every object and use just ValueTransformer for every JSONModel class with NSString property and map it to correct string or empty string if nil/null.
After getting response, run following loop with your response dictionary and its key.
for (id dictionary in [[responseDictionary valueForKey:#"responseKey"] allKeys] )
{
([[responseDictionary valueForKey:#"responseKey"] valueForKey:dictionary] == [NSNull null]) ? [[responseDictionary valueForKey:#"responseKey"] setValue:#"" forKey:dictionary] :[[responseDictionary valueForKey:#"responseKey"] setValue:[[responseDictionary valueForKey:#"responseKey"] valueForKey:dictionary] forKey:dictionary];
}
Is it possible to parse json to an array of JSONModel objects using JSONModel? Like parse json below:
[{"id" : 1}, {"id" : 2}]
to two JSONModel objects having property of "id".
You should use arrayOfModelsFromDictionaries: on your model class like so:
NSArray* models = [YourModelClass arrayOfModelsFromDictionaries: objects];
This will go over "objects" and convert each dictionary to a model and you get the result in models. If any item in objects fail to convert to model "models" will be nil.
Here's the class docs for this method:
http://jsonmodel.com/docs/Classes/JSONModel.html#//api/name/arrayOfModelsFromDictionaries:
Why not trying BWJSONMatcher?
First you should declare your own data model:
#interface MyDataModel : NSObject
#property (nonatomic, assign) NSInteger id;
#end
Then you can easily get your array with BWJSONMatcher within one line:
NSArray *jsonArray = [BWJSONMatcher matchJSON:jsonString withClass:[MyDataModel class]];
Hope this could help you.
I'm trying to run some unit tests to test my mappings with RestKit v0.20, however I am getting an error that my destination object is nil. I have track this down to the fact that the mapping is failing because the sourceType is an NSArray and my destinationType is an NSNumber. I think this is because my mapping keypaths are incorrect. I am trying to map the songCard JSON to my objet. I have included my JSON and mapping test below.
It Would be great it someone could help me to set the correct keypath.
{"status" : 2000,
"content" : {
"cardList" : [
{
"songCard" : {
"likes" : 2,
"dislikes" : 3
}
}
]
},
"message" : "OK"
}
Unit Test class
- (RKObjectMapping *)songMetadataMapping
{
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[SongMetadata class]];
[mapping addAttributeMappingsFromDictionary:#{
#"content.cardList.songCard.likes": #"likes"
}];
return mapping;
}
- (void)testSongMetadataMapping
{
NSString *parsedJSON = [RKTestFixture parsedObjectWithContentsOfFixture:#"songMetadata.json"];
RKMappingTest *test = [RKMappingTest testForMapping:[self songMetadataMapping] sourceObject:parsedJSON destinationObject:nil];
[test addExpectation:[RKPropertyMappingTestExpectation expectationWithSourceKeyPath:#"content.cardList.songCard.likes" destinationKeyPath:#"likes" value:#"2"]];
STAssertTrue([test evaluate], #"Mappings failed");
}
UPDATE
After further debugging I have found that the value 2 in my JSON string is being evaluated as an NSArray, when this should be evaluated as NSNumber. As a quick test I removed the [ ] in my JSON and the value 2 was correctly evaluated as an NSNumber. This doesn't solve my problem though as I have need to identify my JSON as an array of songCard objects
As you have noticed, you cannot use the keypath as you have specified when an array is in play. I can think of two options - the first is a long shot, but does the key path content.cardList[0].songCard.likes work?
Otherwise, consider using the method:
+ (instancetype)expectationWithSourceKeyPath:(NSString *)sourceKeyPath
destinationKeyPath:(NSString *)destinationKeyPath
evaluationBlock:(RKMappingTestExpectationEvaluationBlock)evaluationBlock;
With keypath content.cardList and supplying an evaluation block that 1) checks that the mapping is an array that contains a single object. You can then check that the object contains a songCard object and that has a likes value of 2.