RestKit: displaying an array of JSON strings

Given the following JSON:

{ "someKey":"someValue", "otherKey":"otherValue", "features":[ "feature1", "feature2", "feature3" ] } 

I map this JSON in NSManagedObject to RKMapperOperation and RKEntityMapping (in this example, I would have 2 entity mappings: one for the top-level object and the other for my Feature class).

Displaying top-level objects is trivial: two attribute mappings plus one relationship (function) to relate to Feature.

My question is how to map the functions of a JSON array to an array of Feature objects? The Feature class has only one name property, where I want to store "feature1", "feature2", etc. Plus a link to the parent object (top level). Something like that:

 @interface Feature : NSManagedObject //In the implementation file both properties are declared with @dynamic. @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) MyTopLevelObject *myTopLevelObject; @end 

Any idea?

+4
source share
3 answers

You need to use the nil key path:

 RKEntityMapping *featureMapping = [RKEntityMapping mappingForEntityForName:...]; [featureMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"name"]]; featureMapping.identificationAttributes = @[ @"name" ]; 

Then, in your mapping of top-level objects, define the relationship:

 [topMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"features" toKeyPath:@"features" withMapping:featureMapping]]; 

In your function (in the model), myTopLevelObject should be defined as a bidirectional relation to a top-level object.

+7
source

If you are using Restkit 0.20+, then all you have to do is set a property that represents the string array of your entity to Transformable.

For example, in this case, the Feature object has 3 properties:

 someKey - String otherKey - String features - Transformable 

Restkit will automatically display the "functions" as a string array.

So, after matching to access one of the lines in an array of functions, it would be simple:

[Feature.features objectAtIndex:?]

I just tried it and it works great.

+7
source

I do not think you can match an array of strings in a similar ManagedObject. However, since a function has only one name property, you can simply save it as an array to your MyTopLevelObject . You can do this by adding the features property to MyTopLevelObject in your datamodel of type Transformable . RestKit will automatically analyze NSArray functions using NSStrings. Then you can get the following functions:

 MyTopLevelObject *topLevelObject = ... // get the object from the persistent store NSArray *features = (NSArray*)topLevelObject.features; // this will contain the features as NSString objects 
+1
source

Source: https://habr.com/ru/post/1487002/


All Articles