1

我尝试解析从 REST-Webservice 获得的 JSON。

座位.json:

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

我的 MTLModel (这不起作用。因为 json 字段前面有一个座位。)

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

这将起作用,因为它通过座位字典访问字段。

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

但是嵌套对象将不起作用。示例 JSON:

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

映射:

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

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

这不起作用,因为座位映射仅在字典以座位开头时才有效。

如何将 Mantle SDK 与这样的 JSON 对象一起使用?

4

1 回答 1

0

似乎这seat不是使用初始化对象所需的数据的一部分Mantle,所以我会使用:

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

(或mtl_identityPropertyMapWithModel

然后在解析 JSON 时,只需使用:

NSError *error = nil;
Seat *seat = [MTLJSONAdapter modelOfClass:Seat.class
    fromJSONDictionary:sourceJSON[@"seat"] error:&error];
于 2016-05-29T08:43:10.687 回答