2011-11-05 43 views
1

我正在使用RestKit的對象映射將JSON數據映射到對象。 是否可以將我的Objective-C類中的緯度和經度JSON屬性映射到CLLocation變量?RestKit RKObjectMapping到CLLocation

的JSON:

{ "items": [ 
    { 
     "id": 1, 
     "latitude": "48.197186", 
     "longitude": "16.267452" 
    }, 
    { 
     "id": 2, 
     "latitude": "48.199615", 
     "longitude": "16.309645" 
    } 
] 

}

類應該映射到:

@interface ItemClass : NSObject  
    @property (nonatomic, strong) CLLocation *location; 
@end 

最後,我想打電話itemClassObj.location.longitude讓我的價值來自JSON響應的緯度。

我以爲這樣的事情會起作用,但事實並非如此。

RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ItemClass class]]; 
[mapping mapKeyPath:@"latitude" toAttribute:@"location.latitude"]; 
[mapping mapKeyPath:@"longitude" toAttribute:@"location.longitude"]; 

非常感謝您的幫助。

回答

2

要創建CLLocation,您同時需要經緯度。此外,CLLocation的座標(如CLLocationCoordinate2D)不是NSNumbers,它們是雙浮點數,所以它可以像這樣映射關鍵值合規性,因爲浮點數不是對象。

大多數情況下,人們將經緯度存儲在NSNumbers類中,然後在類對象被實例化/填充後,按需構建CLLocationCoordinate2D座標。

什麼你可能做的,如果你是這樣的傾向,是利用willMapData:委託方法窺探未來的數據,以便手動填充CLLocation ......但對我來說這是矯枉過正,需要太多很多開銷。


編輯:添加這個,因爲意見不格式化代碼屬性...

或者,你可以把這樣的事情在你的對象類實現和接口...

@property (nonatomic,readonly) CLLocationCoordinate2D coordinate; 

- (CLLocationCoordinate2D)coordinate { 
    CLLocationDegrees lat = [self.latitude doubleValue]; 
    CLLocationDegrees lon = [self.longitude doubleValue]; 
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(lat, lon); 
    if (NO == CLLocationCoordinate2DIsValid(coord)) 
     NSLog(@"Invalid Centroid: lat=%lf lon=%lf", lat, lon); 
    return coord; 
} 
+0

是否有一種方法,火災在我的模型中,只要一切都被映射了?然後,我可以簡單地將映射的經緯度值分配給CLLocationCoordinate ... – alex

+0

爲什麼不在您的模型上創建一個只讀屬性來爲您做這個?只要你準備好將它放在地圖上,就可以調用它......由於評論無法格式化代碼,所以請參閱上面的編輯。 –

+0

此外,我認爲就對你的後映射問題的直接反應而言,'objectMapperDidFinishMapping:'? –

3

RestKit增添了ValueTransformer專門爲CLLocation:

https://github.com/RestKit/RKCLLocationValueTransformer

給出的示例JSON:

{ 
    "user": { 
     "name": "Blake Watters", 
     "location": { 
      "latitude": "40.708", 
      "longitude": "74.012" 
     } 
    } 
} 

從給定的JSON映射到用戶對象:

@interface User : NSObject 
@property (nonatomic, copy) NSString *name; 
@property (nonatomic, copy) CLLocation *location; 
@end 

使用RKCLLocationValueTransformer:

#import "RKCLLocationValueTransformer.h" 

RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]]; 
[userMapping addAttributeMappingsFromArray:@[ @"name" ]]; 
RKAttributeMapping *attributeMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"location" toKeyPath:@"location"]; 
attributeMapping.valueTransformer = [RKCLLocationValueTransformer locationValueTransformerWithLatitudeKey:@"latitude" longitudeKey:@"longitude"]; 
[userMapping addPropertyMapping:attributeMapping]; 

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"user" statusCodes:[NSIndexSet indexSetWithIndex:200]];