RestKit如何将mapKeyPath映射到数组索引?

7

我想使用RestKit (OM2)将给定的数组索引映射到一个属性。这是我的JSON:

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

我希望将其映射到这个对象:

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

我无法想出如何将JSON中位置数组的值映射到我的Objective-C类的属性中。目前的映射如下:

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

现在我该如何添加纬度/经度的映射?我尝试了很多方法,但都没有成功。例如:

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

是否有一种方法可以将JSON中的position[0]映射到我的对象中的latitude

1个回答

3
简短回答是不行的- key-value coding 不支持这样的操作。对于集合只支持max、min、avg、sum等聚合操作。
你最好的选择可能是为NOSearchResult添加一个NSArray属性:
// 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

并定义如下映射:
RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[NOSearchResult class]];
[resultMapping mapKeyPath:@"id" toAttribute:@"place_id"];
[resultMapping mapKeyPath:@"position" toAttribute:@"coordinates"];

之后,您可以手动从坐标中分配纬度和经度。
编辑:在对象加载器代理中进行纬度/经度分配可能是一个好地方。
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object;

并且

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;

1
谢谢 - 我已经担心它不起作用。'didLoadObject'这个提示真是太有帮助了! - cellcortex
2
更好的方法是在自定义的获取器和设置器中,操作底层的数组数据结构来处理纬度和经度。 - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接