2011-11-05 65 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]];