RestKit RKObjectMapping到CLLocation

时间:2011-11-05 23:42:48

标签: ios json mapping restkit cllocation

我正在使用RestKit的Object Mapping将JSON数据映射到一个对象。 是否可以将纬度和经度JSON属性映射到Objective-C类中的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 个答案:

答案 0 :(得分:3)

RestKit专门为CLLocation添加了一个ValueTransformer:

https://github.com/RestKit/RKCLLocationValueTransformer

给出示例JSON:

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

从给定的JSON映射到User对象:

@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]];

答案 1 :(得分:2)

要创建CLLocation,您需要同时拥有纬度和经度。此外,CLLocation的坐标(如CLLocationCoordinate2D)不是NSNumbers,它们是双浮点数,因此它可以像这样填充映射中的键值符合性,因为浮点数不是对象。

大多数情况下,人们会将类中的纬度和经度存储为NSNumbers,然后在实例化/填充类对象后按需构建CLLocationCoordinate2D坐标。

可以做什么,如果你是如此倾向于使用willMapData:delegate方法窥探进来的数据,以便手动填充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;
}