I’m using RestKit in my iOS project, and figured non-trivial problem and can’t find solution for it.
I have a json:
[{
"name": "restkit",
"downloads": 2
},
{
"name": "restkit",
"rating": 10.0
}]
and data model: Model.h
@interface Model : NSObject
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * key;
@property (nonatomic, strong) NSString * value;
@end
Those JSON objects loaded in one array, and one of the attributes is a “dynamic” attribute.
After mapping performed in a RestKit I want to be able to have 2 records:
name: "restkit", key: "downloads", value: 2
name: "restkit", key: "rating", value: 10.0
Question: how to map JSON in the beginning into 2 NSObjects as shown in the example above?
This is how I initialize mapping using RestKit and firing requests:
// 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;
};
}];
The problem, is that keys “downloads” and “rating” are dynamic, and it could be any word. I need to parse that ‘on-the-fly’ and show in UI.
Restkit does support such behavior, but only for nested dictionaries.
I did use key-value validation on the model triggered by RestKit to set correct metric key and value to the generic key I want.