我有一些看起来像这样的 json 数据:
{
items: [
{ // object 1
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
]
}
我想使用 Mantle 将这个 json 映射到一个包含两个对象的数组中。
这看起来像下面这样:
@interface MyObject : MTLModel <MTLJSONSerializing>
@property (nonatomic, strong) NSString *myProperty;
@property (nonatomic, strong) NSString *anotherProperty;
@property (nonatomic, strong) NSObject *anObject;
@end
@implementation MyObject
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"myProperty": @"myProperty",
@"anotherProperty" : @"anotherProperty",
@"anObject": @"anObject"
};
}
@end
但是,这需要我在 json 中找到“items”键,然后解析该键中的内容。
相反,我希望 Mantle 为我映射整个对象。所以,我想出了这个解决方案:
@interface MyObjects : MTLModel <MTLJSONSerializing>
@property (nonatomic) NSArray *items;
@end
@implementation MyObjects
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"items": @"items"
};
}
+ (NSValueTransformer *)itemsJSONTransformer
{
return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[MyObject class]];
}
@end
当一切准备就绪并完成后,这将给我留下如下内容
NSArray *myArrayOfObjects = (MyObjects*)myobjects.items;
这一切都很棒,但我相信创建一个“MyObjects”类,只是作为 MyObject 数组的占位符是过大的。有更好的解决方案吗?理想情况下,我在地幔中寻找一个设置(或者比创建两个类只是为了获取一个对象数组更容易的东西)来为我处理根“item”键,这样当这个解析时,它就出来了2 个对象的数组。
谢谢!
最佳答案
在MTLJSONAdapter中我们映射Jsonobject的地方
如果json是object类型,则object应该映射为
object = [MTLJSONAdapter modelOfClass:responseType fromJSONDictionary:jsonObject error:&error];
如果json是数组类型,对象应该映射为
object = [MTLJSONAdapter modelsOfClass:responseType fromJSONArray:jsonObject error:&error];
[
{
{ // object 1
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
}
{
{ // object 1
aProperty: “bValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: “bValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
}
]
如果是这样的话,可以这样映射
object = [MTLJSONAdapter modelsOfClass:responseType fromJSONArray:jsonObject error:&error];
关于ios - 在父对象内映射对象数组 - Mantle iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945663/