2011-07-17 33 views
7

我想將給定的數組索引映射到RestKit(OM2)的屬性。我有這樣的JSON:RestKit mapKeyPath到數組索引

{ 
    "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映射到的性能我的目標-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"]; 

有沒有一種方法來映射position[0]了JSON的到我的對象latitude

回答

3

簡短的答案是否定的 - key-value coding不允許這樣做。對於收集,只支持彙總操作,如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 

,並定義這樣的映射:

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

一個更好的地方會在自定義getter和setter的lat和lon操作底層數組數據結構。 – Jon