美文网首页
关于数据解析

关于数据解析

作者: NateLam | 来源:发表于2016-09-13 16:39 被阅读24次
  1. 遇到字典里面又套了一层字典
    重写基类model的初始化init方法
 - (instancetype)initWithDictionary:(NSDictionary *)dictionary{

    self = [super init];

    if (self) {
        //vc里两句合一句
        [self setValuesForKeysWithDictionary:dictionary];
    }
    return self;
}

然后将这个方法声明出去, 在遇到字典里面又套了一层字典时, 也就是说其中一个key对应一个新的字典

例子
http://v3.wufazhuce.com:8000/api/movie/49/story/1/0

1.png
2.png
3.png

注意里面套着的user, 不要等到cell类的model赋值里面才把这层user解开, 在解析时就顺便解了, 所以把user先创建一个类, 然后作为外层model的一个model属性声明在外层model类.h中, 比如叫

@property (nonatomic, strong) MovieUserModel *userNew;

然后在.m中

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {

    if ([key isEqualToString:@"user"]) {
    
        self.userNew = [[MovieUserModel alloc] initWithDictionary:value];
    
    }

}

这个initWithDictionary就是刚才在基类重写的方法
然后在cell类中用到的时候直接model.userNew.需要用的属性即可

  1. 如果请求下来的数据有诸如title, id的关键字需要过滤

在model类中

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {

    if ([key isEqualToString:@"id"]) {
        self.idNew = value;
    }

}

以后需要调用.id的地方就调用idNew即可

  1. 如果一段解析结果如图所示
JSON结果.png

则解出来的response在VC可以直接, 不用遍历每一个key值

for (NSDictionary *dic in response[@"data"][@"data"]) {
        
            self.dataModel =[[MovieDataModel alloc] initWithDataSource:dic];
        
            [self.dataSource addObject:_dataModel];     
    }

相关文章

网友评论

      本文标题:关于数据解析

      本文链接:https://www.haomeiwen.com/subject/gzimettx.html