RestKit - saving JSON content into a string coredata attribute - ios

I need to parse a JSON web service response containing a key whose children are not known.
For example let's have the following JSON response where the keys of the customData attribute are defined at runtime:
{
"score": 996,
"customData": { "key1": "key1value", "key2": "key2value" },
"isRegistered": true,
"allowOpening": "OK"
}
Would it be possible to save the JSON content of customData into a string coredata attribute?
I've tried with a simple mapping like this:
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:[[self class] description] inManagedObjectStore:managedObjectStore];
[mapping addAttributeMappingsFromDictionary:#{
#"score": #"score",
#"customData":#"customData",
#"isRegistered": #"isRegistered",
#"allowOpening": #"allowOpening"}];
but it doesn't work, customData saved by coredata is always empty.
Many thanks,
DAN

Would it be possible to save the JSON content of customData into a string coredata attribute?
No, because it will be deserialised to a dictionary and there is no converter for that to a string.
You can store it as a dictionary. It you could add a relationship mapping with a dynamic mapping which checks what the keys are and defines the mapping on the fly...

Related

RestKit mapping for JSOG API object

I'm trying to figure out how to realize a mapping of an API response into CoreData objects using RestKit. The API uses JSOG standard. Here is an example:
[
{
"#id": "1",
"name": "Sally",
"friend": {
"#id": "2",
"name": "Bob",
"friend": {
"#id": "3",
"name": "Fred",
"friend": { "#ref": "1" }
}
}
},
{ "#ref": "2" },
{ "#ref": "3" }
]
How would I create an RKEntityMapping for such a JSON? Mapping of simple attributes is trivial, the question is how to setup the relationships here so they work with #ref, also, when the top level user object contains the #ref only.
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:#"Question"
inManagedObjectStore:[RKObjectManager sharedManager].managedObjectStore];
[userMapping addAttributeMappingsFromDictionary:#
{
#"#id" : #"identifier",
#"name" : #"name"
}];
[userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"friend"
toKeyPath:#"friend"
withMapping:userMapping]];
My guess is that i could use code below to handle the #ref inside of an object:
[userMapping addConnectionForRelationship:#"friend" connectedBy:#{#"#ref": #"#id"}];
but is it correct?
How would I map either a full object or just a reference to an already-provided object (via #ref) to actual Core Data objects?
How can I map the top elements of the JSON (being a list of User objects) to an actual list of User entities?
Add a relationship using the mapping itself, so it drills recursively. Use foreign key mapping for the refs.
Looking at this again following your comment it may actually be a good candidate for a dynamic mapping instead of foreign key. This would mean creating a new mapping which just uses #"#ref" : #"identifier" for the connections and a dynamic mapping which looks at the keys and decides wether to use this connection mapping or the full userMapping.
Note that both of these mappings need to specify that identifier is the unique key of the object and you should use a memory cache to allow the existing objects to be found instead of creating duplicates.

RestKit: Map nested Array to Object

I have two classes to map a JSON response: Item and FrequentProps
Item has the following properties:
frequentProps, identifier, name
FrequentProps has the properties
propOne
propTwo
propThree
propFour
You can see that frequentProps in Item is of type FrequentProps.
Consider the following JSON Response:
[
{
"frequentProps": [
{
"propOne": 174
},
{
"propTwo": 9.726
},
{
"propThree": 2.021
},
{
"propFour": 25.07
}
],
"identifier": "4223",
"name": "TheName"
}
]
The outer part of the JSON is supposed to be mapped to an object of class Item, the nested Array is supposed to be mapped to frequentProps, as a property of the object. Unfortunately, frequentProps is not mapped to the Items property with the same name but into an NSArray (if I define the type of the property as NSArray, otherwise the property remains nil).
Here's the configuration:
RKObjectMapping *itemMapping = [RKObjectMapping mappingForClass:[Item class]];
[item addAttributeMappingsFromDictionary:[Item attributesMapping]];
RKObjectMapping *frequentPropsMapping = [RKObjectMapping mappingForClass:[FrequentProps class]];
[frequentPropsMapping addAttributeMappingsFromDictionary:[FrequentProps attributesMapping]];
[itemMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"frequentProps"
toKeyPath:#"frequentProps"
withMapping:frequentProps]];
// adding the response descriptor, etc...
How can I map the frequentProps directly into an object of type FrequentProps, which remains a property of Item?
You can't, because there is no way in the mapping to specify that you are indexing into an array and putting that index into a specified key. I expect that this will never be supported.
Not ideal but: What you could do it to add the array property as well, with a custom setter method. When the setter is called, mutate the data by creating an instance of FrequentProps and setting the properties from the array contents.

How to serialize an array of Core Data objects into an array of string using RestKit?

I am currently using RestKit version 0.20.3 in my iOS project to communicate with my backend web service.
In some cases, my web service returns an array of tags (django-taggit) in string format and I needed to map each tag string into a core data entity.
// example JSON from web service
"response" : { "tags": ["tag1", "tag2", "tag3"] }
// example Core Data entities
#interface TagEntity : NSManagedObject
#property (nonatomic, retain) NSString *tagName;
#end
From the below discussion, I found a way to map an array of tag strings into core data objects.
https://groups.google.com/forum/#!topic/restkit/54eZFQIjl7c
tagEntityMapping = [RKEntityMapping mappingForEntityForName:#"TagEntity" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
[tagEntityMapping addPropertyMapping:[RKAttributeMapping mappingFromKeyPath:nil toKeyPath:#"tagName"]]
tagEntityMapping.identificationAttributes = #[#"tagName"];
[resultEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"tags" toKeyPath:#"tags"withMapping:tagEntityMapping]];
Now, I am looking for a way to post an array of tag strings from Core Data objects to web service.
In other words, given that I have an array of TagEntity Core Data objects, I wish to send an array of [TagEntity tagName]
To achieve this, I used [resultEntityMapping inverseMapping] as a request mapping, but as result, I get
"request" : { "tags": [{"tag1": {}}, {"tag2": {}}, {"tag3": {}}] }
while what I really wish to get is
"request" : { "tags": ["tag1", "tag2", "tag3"] }
I would appreciate any help. Thanks!
If you just have an array of TagEntity instances then you can get the array of strings with:
NSArray *tagStrings = [tags valueForKey:#"tagName"];
Once you have that you can pass the array to RestKit (wrapped into an NSDictionary based on your sample JSON) or use NSJSONSerialization directly and use the underlying AFNetworking provided API to send the JSON.

Reskit - Mapping to array

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.

RestKit primary key attribute

I load data from a json file, I save it.
I do it twice ...
I got two entries in my Core Data sqlite database.
Even if I set in the mapping the primaryKeyAttribute.
mapping.primaryKeyAttribute = #"code";
[mapping mapAttributesFromArray :mappedFields];
[[RKObjectManager sharedManager].mappingProvider setMapping:mapping forKeyPath:entityName];
My Json
{ "MyEntity": [ { "code" : "axv2","data" : "content"}]};
Here the callback :
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
NSLog(#"Entries loaded %d",[objects count]);
lastResult = objects;
for(MyEntity * myEntity in lastResult) {
[self saveContext];
}
}
My entity is correctly mapped ... But Restkit allow one to save duplicate entries with the same primary key?
It's weird, I understood that this primary key attribute would avoid this problem.
No, that is not the case, as Core Data keeps its own keys. You can easily solve this problem by checking if your primary key exists and before saving the entity instance in question.
As of the latest RESTKit version (0.23.2) you can define the primary key like this:
[_mapping addAttributeMappingsFromDictionary:#{ #"id" : #"objectId", #"name" : #"name" }];
[_mapping setIdentificationAttributes:#[ #"objectId" ]];
Whereas objectId is you primary key on the core data object.

Resources