mixtly87
mixtly87

Reputation: 1715

How to map this JSON array to objects in RestKit 2

I have a JSON structure like this:

[
    {
        "id" : "1",
        "name" : "Group 1"
    },
    {
        "id" : "2",
        "name" : "Group 2"
    },
    {
        "id" : "3",
        "name" : "Group 3"
    }
]

Please pay attention it begins with [ and ends with ]. How to map this-like JSON to array of Group objects using RestKit 2?

I tried with classic:

RKObjectMapping* groupMapping = [RKObjectMapping mappingForClass:[Group class]];
[groupMapping addAttributeMappingsFromDictionary:@{
        @"id" : @"groupID",
        @"name" : @"name"
}];
return groupMapping;

Then I'm using RKMappingTest to verify mapping, but I'm usually getting error:

restkit.object_mapping:RKMappingOperation.m:440 Failed transformation of value at keyPath 'id' to representation of type 'NSString': Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 "Failed transformation of value...

After parsing of JSON with:

_parsedJSON = [RKTestFixture parsedObjectWithContentsOfFixture:@"groups.json"];

_parsedJSON is an array of dictionaries.

Upvotes: 0

Views: 1047

Answers (1)

Wain
Wain

Reputation: 119041

Failed transformation of value at keyPath 'id'

This is because it can't convert an array to a string.

The type of test your using cannot handle this JSON because it isn't a single mapping, it's multiple mappings, and the multiplicity is not handled by the mapping class.

When the mapping runs, it calls valueForKey: on an array and gets an array back. It expects to be calling on a dictionary and getting a string (or number).

So, basically, only test mapping individual objects.

Upvotes: 1

Related Questions