RestKit mapping for JSOG API object - ios

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.

Related

RestKit - saving JSON content into a string coredata attribute

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...

RestKit: Ignoring some dynamic nesting attributes

I receive JSON objects like this:
{
"rent": {
"id": "someId"
},
"upcoming": {
"id": "someId"
},
"watchnow": {
"id": "someId"
}
}
I then set forceCollectionMapping to YES on my mapping to get one object for each key, i.e. one object for "rent", one for "upcoming" and one for "watchnow". Specifically this is done with this code:
[searchResultsMapping addAttributeMappingFromKeyOfRepresentationToAttribute:#"searchSection"];
So this succesfully gives me three objects for which I can then do some relationship mapping to get the id keys and what ever else is on the object.
Now, my problem is that if an error occurs, I get this JSON code:
{
"error": {
"errorcode": "someId"
}
}
So (searchSection) becomes "error" and my relationship mapping looks for "id" but it's not there so the mapping fails. The problem is that setting addAttributeMappingFromKeyOfRepresentationToAttribute makes RestKit try to make an object from every single key, and I can't expect every key to be relevant and useful for my mappings. Can I do anything about this?
You have a couple of options:
Use an RKDynamicMapping as the root mapping for your response descriptor
Use multiple response descriptors to specify exactly which keypaths to process
Use KVC validation to reject the error mapping (not ideal as the error isn't really captured)
For the dynamic mapping option, the dynamic mapping has the forceCollectionMapping option set and it checks the top level key available and returns the appropriate mapping (which wouldn't have forceCollectionMapping set and which uses addAttributeMappingFromKeyOfRepresentationToAttribute:).
I got it to work using Wain's first suggestion. Here's the solution if anyone has the same issue:
I created a dynamic mapping like this:
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
dynamicMapping.forceCollectionMapping = YES;
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping * (id representation) {
if ([representation valueForKey:#"watchnow"] || [representation valueForKey:#"upcoming"] || [representation valueForKey:#"rent"]) {
return searchResultsMapping;
}
return nil;
}];
As you can see in my example at the top, I'm only interested in keys named "watchnow", "upcoming" or "rent".
The searchResultsMapping which is returned is configured like this:
RKObjectMapping *searchResultsMapping = [RKObjectMapping mappingForClass:[TDXSearchResults class]];
[searchResultsMapping addAttributeMappingFromKeyOfRepresentationToAttribute:#"searchSection"];
So I now end up with three SearchResult objects with either "watchnow", "upcoming" or "rent" in their searchSection NSString property.

Restkit — How to map json objects with mutable key names

I have to map this structure, but I don't know how to identify the "br.myservice.com" part, because it changes and I cannot build a regular RKObjectMapping, as it uses fixed strings.
{ "objects": {
"br.myservice.com": {
"url": "http://br.myservice.com",
"name": "Brazil",
"flag": "br",
"countries": ["br"]
},
"us.myservice.com": {
"url": "http://us.myservice.com",
"name": "United States",
"flag": "us",
"countries": ["us"]
}
}
You need to use addAttributeMappingFromKeyOfRepresentationToAttribute: like so:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[MyObject class]];
mapping.forceCollectionMapping = YES;
[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:#"host"];
[mapping addAttributeMappingsFromDictionary:#{
#"(host).url": #"url",
#"(host).name": #"name",
... and so on ....
}];
Assuming that the keys are unknown to you at the time of writing the code:
You would need to create a dynamic mapping (RKDynamicMapping) with a block which inspects the received JSON dictionary and creates (and returns) a custom object mapping on the fly.
If you know the keys, just add them all and any that are appropriate will be used at runtime.

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.

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