gpt4 book ai didi

ios - RestKit RKObjectMapping 到 CLLocation

转载 作者:行者123 更新时间:2023-12-01 18:02:06 25 4
gpt4 key购买 nike

我正在使用 RestKit 的对象映射将 JSON 数据映射到对象。
是否可以将纬度和经度 JSON 属性映射到 CLLocation我的 Objective-C 类中的变量?

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

非常感谢你的帮助。

最佳答案

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

关于ios - RestKit RKObjectMapping 到 CLLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8024176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com