简体   繁体   English

使用具有根键的Mantle解析JSON

[英]Parse JSON with Mantle which has Root Keys

I try to parse the JSON I get from a REST-Webservice. 我尝试解析从REST Web服务获得的JSON。

Seat.json: 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.) 我的MTLModel(这不起作用。因为json字段前面有一个座位。)

+ (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: 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. 这将不起作用,因为仅当字典以seat开头时,座位映射才会起作用。

How can I use the Mantle SDK with JSON Objects like that? 如何将Mantle SDK与类似的JSON对象一起使用?

It seems that seat is not part of the data needed to initialize the object using Mantle , So I would use: 似乎seat不是使用Mantle初始化对象所需的数据的一部分,所以我将使用:

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

(Or mtl_identityPropertyMapWithModel ) (或mtl_identityPropertyMapWithModel

Then when Parsing the JSON just use: 然后在解析JSON时只需使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM