我使用RestKit的对象映射将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"];非常感谢你的帮助。
发布于 2011-11-07 04:45:54
要创建CLLocation,您需要同时提供纬度和经度。此外,CLLocation (像CLLocationCoordinate2D)的坐标不是NSNumbers,它们是双浮点数,所以它可以像这样提升映射中的键值遵从性,因为浮点数不是对象。
大多数情况下,人们会将纬度和经度作为NSNumbers存储在类中,然后在实例化/填充类对象后按需构建CLLocationCoordinate2D坐标。
如果您愿意的话,您可以利用willMapData: delegate方法来监听传入的数据,以便手动填充CLLocation ...但对我来说,这太夸张了,需要太多的开销。
EDIT:添加此代码,因为注释不会格式化代码属性...
或者,您可以在您的对象类实现和接口中放入类似这样的内容...
@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;
}发布于 2014-05-21 11:37:05
RestKit专门为CLLocation添加了一个ValueTransformer:
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]];https://stackoverflow.com/questions/8024176
复制相似问题