Mapping a JSON array of unnamed values with RESTKI

2019-07-21 07:17发布

问题:

When I configure mapping from a REST service returning JSON to a object, I normally do this:

RKObjectMapping *myMapping = [RKObjectMapping mappingForClass:[MyClass class]];
[myMapping addAttributeMappingsFromDictionary:@{@"Address" : @"address", @"City" : @"city"}];

and this works great for JSON with named attributes, but how do I map the following JSON to a object with the property "name"?

["My Value","Some other value","More stuff","Hello World"]

This JSON is just a array of values and has not name/key only values. How do I map this to a object with RESTKIT 0.20?

Thank you
Søren

回答1:

This expression in square brackets is a json array: http://www.json.org. If you look on the syntax tree on the home page, you can consider, every json array is a value of a "variable" with a name. It means your expression has to look like this, to be a valid json:

{ "myArray": ["My Value","Some other value","More stuff","Hello World"] }

and you map it like you always do:

[myMapping addAttributeMappingsFromDictionary:@{@"myArray" : @"myArray"}];

Your parameter MyArray in mapping target class has then a type of NSArray.



标签: restkit