iOS:使用Mantle转换对象数组

时间:2018-10-28 06:34:06

标签: ios json github-mantle

我正在使用Mantle序列化json字符串。

这是服务器返回的json

"data": {
        "rows": {
        "0": {
            "id": 1,
            "rate": "13",
            "cycle": "22",
            "amount": "16",
            "name": "Nikita Kulas"
        },
        "1": {
            "id": 2,
            "rate": "14",
            "cycle": "25",
            "amount": "22",
            "name": "Nikita Kulas"
        },
        "2": {
            "id": 3,
            "rate": "7",
            "cycle": "8",
            "amount": "4",
            "name": "Nikita Kulas"
        },
        "4": {
            "id": 10,
            "rate": "18",
            "cycle": "24",
            "amount": "5",
            "name": "Nikita Kulas"
        }
    }
}

模型类是:

@interface QuantProduct : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy, readonly) NSNumber *qpId;
@property (nonatomic, copy, readonly) NSString *requirement;
@property (nonatomic, copy, readonly) NSString *period;
@property (nonatomic, copy, readonly) NSString *rate;
@property (nonatomic, copy, readonly) NSString *name;

@end

@interface QuantProductList : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy) NSArray<QuantProduct *> *quantProductList;

@end

@implementation QuantProduct


+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"qpId": @"id",
             @"name": @"name",
             @"requirement": @"amount",
             @"period": @"cycle",
             @"rate": @"rate"
             };
}

@end

@implementation QuantProductList

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"quantProductList" : @"rows"
             };
}

+ (NSValueTransformer *)quantProductListJSONTransformer {
    return [MTLJSONAdapter arrayTransformerWithModelClass:[QuantProduct class]];
}


@end

我尝试使用arrayTransformerWithModelClass,但是它不是一个直线数组。

在json中,索引键不是固定数字,所以我应该如何修改JSONTransformer方法以直接序列化json?

谢谢

0 个答案:

没有答案