基于JSONModel属性的动态模型级联

时间:2015-07-30 09:19:02

标签: ios objective-c jsonmodel

给出以下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属性自动创建其中一个模型类?

2 个答案:

答案 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];
        }
    }

然后您可以迭代audioModelArrayvideoModelArray个对象来访问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;
}