Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestKit: mapping JSON array of strings

Given the following JSON:

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

I am mapping this JSON into NSManagedObjects with RKMapperOperation and RKEntityMapping(in this example I would have 2 entity mappings: one for the top level object and another one for my Feature class).

The top level object mapping is trivial: two attribute mappings plus a relationship one(features) for the relation with Feature.

My question is,how to map the features JSON array into an array of Feature objects? The Feature class has just one property name where I want to store "feature1", "feature2", etc plus a reference to the parent object (the top level one). Something like this:

@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?

like image 443
e1985 Avatar asked Dec 06 '22 07:12

e1985


2 Answers

You need to use a nil key path:

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

Then, on your top level object mapping, define the relationship:

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

In your feature (in the model), myTopLevelObject should be defined as a bi-directional relationship to the top level object.

like image 98
Wain Avatar answered Jan 01 '23 20:01

Wain


If you are using Restkit 0.20+ then all you need to do is set the property that is representing the string array of your entity to Transformable.

For example, in this case your Feature entity has 3 properties:

someKey - String
otherKey - String
features - Transformable

Restkit will automatically map 'features' as a string array.

So once mapped, to access one of the strings in the features array would be as simple as:

[Feature.features objectAtIndex:?]

I just tried it and it works perfect.

like image 33
Jesse Avatar answered Jan 01 '23 20:01

Jesse