给出以下JSON blob:
[
{
type: "audio",
title: "Audio example title",
},
{
type: "video",
title: "Video example title",
},
{
type: "audio",
title: "Another audio example title",
},
]
和两个JSONModel模型类(AudioModel,VideoModel)。是否可以让JSONModel在将JSON映射到模型时根据type
属性自动创建其中一个模型类?
答案 0 :(得分:0)
可以使用for..in
循环并检查type属性并根据下面的类型创建Model对象
NSMutableArray *audioModelArray = [NSMutableArray alloc] init];
NSMutableArray *videoModelArray = [NSMutableArray alloc] init];
for(NSdictionary *jsonDict in jsonArray) {
if(jsonDict[@"type"] isEqualToString:@"audio") {
AudioModel *audio = [AudioModel alloc]initWithTitle:jsonDict[@"title"]];
[audioModelArray addObject: audio];
} else {
VideoModel *audio = [VideoModel alloc] initWithTitle:jsonDict[@"title"]];
[videoModelArray addObject: audio];
}
}
然后您可以迭代audioModelArray
和videoModelArray
个对象来访问audoModel和videoModel对象及其属性。
答案 1 :(得分:0)
在JSONModel贡献者之间发生了相当多的讨论。结论似乎是实现自己的类集群是最好的选择。
如何执行此操作的示例 - 从my comment on the GitHub issue复制:
+ (Class)subclassForType:(NSInteger)pipeType
{
switch (pipeType)
{
case 1: return MyClassOne.class;
case 2: return MyClassTwo.class;
}
return nil;
}
// JSONModel calls this
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)error
{
if ([self isExclusiveSubclass])
return [super initWithDictionary:dict error:error];
self = nil;
NSInteger type = [dict[@"type"] integerValue];
Class class = [MyClass subclassForType:type];
return [[class alloc] initWithDictionary:dict error:error];
}
// returns true if class is a subclass of MyClass (false if class is MyClass)
- (BOOL)isExclusiveSubclass
{
if (![self isKindOfClass:MyClass.class])
return false;
if ([self isMemberOfClass:MyClass.class])
return false;
return true;
}