我在我的 iOS 项目中使用 RestKit,并发现了一个不平凡的问题,但找不到解决方案。
我有一个json:
[{
"name": "restkit",
"downloads": 2
},
{
"name": "restkit",
"rating": 10.0
}]
和数据模型:Model.h
@interface Model : NSObject
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * key;
@property (nonatomic, strong) NSString * value;
@end
这些 JSON 对象加载在一个数组中,其中一个属性是“动态”属性。在 RestKit 中执行映射后,我希望能够有 2 条记录:
name: "restkit", key: "downloads", value: 2
name: "restkit", key: "rating", value: 10.0
问题:如上例所示,如何将开头的 JSON 映射为 2 个 NSObject?
这就是我使用 RestKit 初始化映射和触发请求的方式:
// during app initialization I setup mappings:
RKObjectMapping *modelMapping = [RKObjectMapping mappingForClass:[Model class]];
[metricDataMapping mapKeyPath:@"name" toAttribute:@"name"];
...... -- something should go here to support that dynamic stuff
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:metricDataMapping];
// in the view controller when loading data
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:url usingBlock:^(RKObjectLoader *loader){
loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass: [MetricData class]];
loader.onDidLoadObjects = ^(NSArray * objects){
self.dataArray = objects;
};
}];
问题在于“下载”和“评级”键是动态的,它可以是任何词。我需要解析“即时”并在 UI 中显示。Restkit 确实支持这种行为,但仅适用于嵌套字典。