2

给定以下 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 在type将 JSON 映射到模型时根据属性自动创建其中一个模型类?

4

2 回答 2

0

可以使用for..in循环并检查类型属性并根据以下类型创建模型对象

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

然后您可以遍历对象来访问 audoModelaudioModelArrayvideoModelArrayvideoModel 对象及其属性。

于 2015-07-30T09:54:36.267 回答
0

JSONModel 贡献者之间围绕这个问题进行了相当多的讨论。结论似乎是实现自己的类集群是最好的选择。

如何做到这一点的一个例子 - 从我对 GitHub 问题的评论中复制:

+ (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;
}
于 2016-01-12T12:15:23.167 回答