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

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


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;
链接地址: http://www.djcxy.com/p/8670.html

上一篇: git日志只返回对主分支进行的提交?

下一篇: 将映射关系映射到数组索引