RestKit mapKeyPath to Array索引

cel*_*tex 7 iphone json objective-c restkit

我想将给定的数组索引映射到具有RestKit(OM2)的属性.我有这个JSON:

{
  "id": "foo",
  "position": [52.63, 11.37]
}
Run Code Online (Sandbox Code Playgroud)

我想映射到这个对象:

@interface NOSearchResult : NSObject
@property(retain) NSString* place_id;
@property(retain) NSNumber* latitude;
@property(retain) NSNumber* longitude;
@end
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何将我的JSON中的位置数组中的值映射到我的objective-c类的属性中.到目前为止,映射看起来像这样:

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[NOSearchResult class]];
[resultMapping mapKeyPath:@"id" toAttribute:@"place_id"];
Run Code Online (Sandbox Code Playgroud)

现在我如何添加纬度/经度的映射?我尝试了各种不行的东西.例如:

[resultMapping mapKeyPath:@"position[0]" toAttribute:@"latitude"];
[resultMapping mapKeyPath:@"position.1" toAttribute:@"longitude"];
Run Code Online (Sandbox Code Playgroud)

有没有办法position[0]将JSON 映射到latitude我的对象中?

Vic*_* K. 3

简而言之,答案是否定的——键值编码不允许这样做。对于集合,仅支持 max、min、avg、sum 等聚合操作。

您最好的选择可能是将 NSArray 属性添加到 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
Run Code Online (Sandbox Code Playgroud)

并像这样定义映射:

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[NOSearchResult class]];
[resultMapping mapKeyPath:@"id" toAttribute:@"place_id"];
[resultMapping mapKeyPath:@"position" toAttribute:@"coordinates"];
Run Code Online (Sandbox Code Playgroud)

之后,您可以从坐标手动分配纬度和经度。

编辑:进行纬度/经度分配的好地方可能是在对象加载器委托中

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object;
Run Code Online (Sandbox Code Playgroud)

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;
Run Code Online (Sandbox Code Playgroud)

  • 更好的地方是使用 lat 和 lon 的自定义 getter 和 setter 来操作底层数组数据结构。 (2认同)