Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestKit mapKeyPath to Array index

I would like to map a given array index into a property with RestKit (OM2). I have this JSON:

{
  "id": "foo",
  "position": [52.63, 11.37]
}

which I would like to map to this Object:

@interface NOSearchResult : NSObject
@property(retain) NSString* place_id;
@property(retain) NSNumber* latitude;
@property(retain) NSNumber* longitude;
@end

I can't figure out how to map values out of the position array in my JSON into properties of my objective-c class. The mapping looks like this so far:

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[NOSearchResult class]];
[resultMapping mapKeyPath:@"id" toAttribute:@"place_id"];

Now how can I add a mapping for the latitude/longitude? I tried various things, that don't work. e.g.:

[resultMapping mapKeyPath:@"position[0]" toAttribute:@"latitude"];
[resultMapping mapKeyPath:@"position.1" toAttribute:@"longitude"];

Is there a way to map position[0] out of the JSON into latitude in my object?

like image 485
cellcortex Avatar asked Jul 17 '11 08:07

cellcortex


1 Answers

The short answer is no - key-value coding doesn't allow for that. For collection, only aggregate operations such as max, min, avg, sum are supported.

Your best bet is probably to add an NSArray property to NOSearchResult:

// NOSearchResult definition
@interface NOSearchResult : NSObject
@property(retain) NSString* place_id;
@property(retain) NSString* latitude;
@property(retain) NSNumber* longitude;
@property(retain) NSArray* coordinates;
@end

@implementation NOSearchResult
@synthesize place_id, latitude, longitude, coordinates;
@end

and define mapping like this:

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[NOSearchResult class]];
[resultMapping mapKeyPath:@"id" toAttribute:@"place_id"];
[resultMapping mapKeyPath:@"position" toAttribute:@"coordinates"];

After that, you could manually assign latitude and longitude from coordinates.

EDIT: A good place to do latitude/longitude assignment is probably in object loader delegates

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object;

and

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;
like image 86
Victor K. Avatar answered Sep 28 '22 07:09

Victor K.