iOS数据解析

作者: myk | 来源:发表于2018-06-15 16:01 被阅读130次
    • 从服务器获取数据之后,接下来我们就需要对数据进行解析,转换成模型;有时候数据比较复杂,搞得我头晕脑胀的,就记录一下
    • 数据是这样的


      数据样式.png
    • 取出 templist 数组里面的字典,然后字典里面又有一个数组 Labels
    • 创建两个模型,一个是 templist 里面的字典的模型,另外一个是字典里面的的Labels的字典里面的模型
    #import <Foundation/Foundation.h>
    
    @interface ModelLabel : NSObject
    
    @property (nonatomic, copy) NSString *content;
    @property (nonatomic, copy) NSString *fontcolor;
    @property (nonatomic, copy) NSString *bgcolor;
    
    +(instancetype)modelWithDict:(NSDictionary *)dict;
    
    @end
    
    #import "ModelLabel.h"
    
    @implementation ModelLabel
    
    +(instancetype)modelWithDict:(NSDictionary *)dict{
        return [[self alloc] initWithDict:dict];
    }
    
    -(instancetype)initWithDict:(NSDictionary *)dict{
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dict];
        }
        return self;
    }
    
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
        
    }
    
    @end
    
    
    .h
    #import <Foundation/Foundation.h>
    #import "ModelLabel.h"
    
    @interface ModelList : NSObject
    
    @property (nonatomic, copy) NSString *time_waitpost;
    @property (nonatomic, copy) NSString *bizname;
    @property (nonatomic, copy) NSString *bizaddress;
    @property (nonatomic, copy) NSString *receiver_name;
    @property (nonatomic, copy) NSString *receiver_address;
    @property (nonatomic, copy) NSArray <ModelLabel *>*arrLabel;
    
    +(instancetype)modelWithDict:(NSDictionary *)dict;
    
    @end
    
    .m
    #import "ModelList.h"
    @implementation ModelList
    
    +(instancetype)modelWithDict:(NSDictionary *)dict{
        return [[self alloc] initWithDict:dict];
    }
    
    -(instancetype)initWithDict:(NSDictionary *)dict{
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dict];
            NSMutableArray *arr = [NSMutableArray array];
            //取出Labels数组里面的数据转换成ModelLabel模型,如果是模型里面嵌套有其他模型,需要在这里调用其他模型的转模型方法
            NSArray *arrTemp = dict[@"Labels"];
            for (NSDictionary *dictTemp in arrTemp) {
                [arr addObject:[ModelLabel modelWithDict:dictTemp]];
            }
            self.arrLabel = [arr copy];
        }
        return self;
    }
    
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
        
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:iOS数据解析

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