美文网首页
根据json字典生成对应的model(懒人专用)

根据json字典生成对应的model(懒人专用)

作者: 辛乐 | 来源:发表于2018-07-10 16:52 被阅读11次

开发中经常需要用到根据json数据去创建对应的模型,这里说的是OC版本
如下边的json数据

{
    "Attention": {
        "isAttention": 0,
        "attentionId": "",
        "mediaId": 2,
        "logo": "http://wzimg.fxeye.com/whtt/logo_2.jpg-none",
        "mediaName": "中金网",
        "desc": "你的外汇头条",
        "state": 1,
        "fans": 0,
        "gbImg": "http://wzimg.fxeye.com/whtt/bg_2.jpg-none",
        "profile": "你的外汇头条",
        "newsCount": 504,
        "mediaType": 1,
        "vip": 1
    },
    "collectId": null,
    "code": "a2018061225990475",
    "title": "10年内230万个金22",
    "zhaiyao": "xxxxxx",
    "url": "http://news.cngold.com.cn/a2018061225990475.html",
    "img": "http://imgoss.cngold.com.cn/2018/6/12/2018061210265784089989.jpg-ttlist",
    "mediaid": "2",
    "medianame": "中金网",
    "mediatype": 1,
    "refermedia": "",
    "extent1": "COB_20180612d1703n25990475",
    "extend2": "",
    "showtime": "2018-06-12T11:14:28"
}

方法一
极力推荐一个插件吧地址👉: https://github.com/keepyounger/Json2Property
具体使用方法对应开发者介绍的很清楚,这里注意的是一定保证json数据格式的正确性,可以用相应的json格式校验工具进行校验,这里就不在详细说明了

方法二
作为程序员,当然会去思考它内部可能是怎么实现的呢,或者我自己会怎么实现呢?强迫症又来了,直接上代码

//字典转成model字符串 [dic:json字典 isUseDicTypeProperty:是否使用字典属性]
+(NSString *)getModelStrByDic:(NSDictionary *)dic IsUseDicTypeProperty:(BOOL) isUseDicTypeProperty{
    NSString *modelStr = @"";
    NSArray *keysArr = dic.allKeys;
    for (NSString *key in keysArr) {
        
        id value = dic[key];
        NSString *str = @"";
        if ([value isKindOfClass:[NSArray class]]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, strong)NSArray *%@;\n",key];
        }else if ([value isKindOfClass:[NSDictionary class]]){
            
            if (isUseDicTypeProperty) {
                //1.0直接使用字典属性
                str = [NSString stringWithFormat:@"@property (nonatomic, strong)NSDictionary *%@;\n",key];
            }else{
                //2.0字典再解析
                str = [NSString stringWithFormat:@"@property (nonatomic, strong)XL%@Model *%@;\n",key,key];
                str = [NSString stringWithFormat:@"@interface XL%@Model : NSObject \n%@ @end\n %@",key,[self getModelStrByDic:value],str];
            }
        }else if ([value isKindOfClass:[NSNumber class]]){
            str = [NSString stringWithFormat:@"@property (nonatomic, assign)NSInteger %@;\n",key];
        }else{
            str = [NSString stringWithFormat:@"@property (nonatomic, strong)NSString *%@;\n",key];
        }
        modelStr = [NSString stringWithFormat:@"%@%@",modelStr,str];
    }
    return modelStr;
}

实际运行如下:


step1.png step2.png

只是窥探内部可能实现机制,当然还是使用现成插件去啊~~

相关文章

网友评论

      本文标题:根据json字典生成对应的model(懒人专用)

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