Parse JSON with Mantle which has Root Keys

226 views Asked by At

I try to parse the JSON I get from a REST-Webservice.

Seat.json:

{"seat":{ "row":1,
          "seatNr":1,
          "seatId":5782}}

My MTLModel (This does not work. Because there is a seat in front of the json fields.)

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
         @"seatId"  :@"seatId",
         @"row"     :@"row",
         @"seatNr"  :@"seatNr"};
}

This will work because it accesses the fields through the seat dictionary.

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
         @"seatId"  :@"seat.seatId",
         @"row"     :@"seat.row",
         @"seatNr"  :@"seat.seatNr"};
}

But then nested objects won't work. Example JSON:

{"participant": {"name":"Test User",
                 "participantId":4243,
                 "chosenSeat":{"row":1,
                         "seatNr":21,
                         "seatId":5802}
                }

Mapping:

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
         @"name"            : @"participant.name",
         @"participantId"   : @"participant.participantId",
         @"seat"            : @"participant.chosenSeat"};
}

+ (NSValueTransformer *)seatJSONTransformer {
    return [MTLJSONAdapter dictionaryTransformerWithModelClass:Seat.class];
}

This won't work, because the seat mapping will only work if the dictionary starts with seat.

How can I use the Mantle SDK with JSON Objects like that?

1

There are 1 answers

0
Lior Bar On

It seems that seat is not part of the data needed to initialize the object using Mantle, So I would use:

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
         @"seatId"  :@"seatId",
         @"row"     :@"row",
         @"seatNr"  :@"seatNr"};
}

(Or mtl_identityPropertyMapWithModel)

Then when Parsing the JSON just use:

NSError *error = nil;
Seat *seat = [MTLJSONAdapter modelOfClass:Seat.class
    fromJSONDictionary:sourceJSON[@"seat"] error:&error];