父对象内部对象的映射数组-iOS
我有一些json数据如下所示:父对象内部对象的映射数组-iOS,ios,objective-c,github-mantle,Ios,Objective C,Github Mantle,我有一些json数据如下所示: { items: [ { // object 1 aProperty: "aValue", anotherProperty: "anotherValue", anObjectProperty: {} }, { //object 2
{
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
这一切都很好,但我认为创建一个“MyObjects”类,只是为了成为MyObject数组的占位符,这是过分的。有更好的解决办法吗?理想情况下,我正在mantle中寻找一个处理根“item”键的设置(或者比创建两个类只是为了获得一个对象数组更容易的设置),这样在解析时,它就变成了一个包含两个对象的数组
谢谢 在MTLJSONAdapter中映射Jsonobject的地方 如果json是对象类型,则该对象应映射为
object = [MTLJSONAdapter modelOfClass:responseType fromJSONDictionary:jsonObject error:&error];
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: {}
}
}
]
如果json是数组类型,则对象应映射为
object = [MTLJSONAdapter modelOfClass:responseType fromJSONDictionary:jsonObject error:&error];
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];
这还有一件事,为了避免创建
MyObjects
类,如果我没有弄错的话,您可以使用object=[MTLJSONAdapter modelsOfClass:responseType fromJSONArray:jsonObject[@“items”]error:&error]
。您找到了更好的解决方案吗?请尝试对答案添加一些解释。只有代码的答案通常被认为是低质量的。
NSArray *myArrayOfObjects = [MTLJSONAdapter modelsOfClass:responseType
fromJSONArray:jsonObject[@"items"]
error:&error]