ios-json数据转模型

先介绍下什么是json

全称是JavaScript Object Notation

json是JavaScript中的对象,在JavaScript中解析json对象很方便

json具有自我描述性,很容易理解

通常在网络传输数据的时候回使用json或者xml,json比xml使用更好广泛,因为更加好理解和方便。

json中的值可以是数字(整数或者浮点数)、字符串(在双引号中)、逻辑值(true或false)、数组(在方括号中)、对象(在花括号中)、null

json数据转模型和plist基本相同,都是懒加载数组

//模型中的类方法,解析字典
+(instancetype)productWithDitc:(NSDictionary *)dict
{
    Product * p=[[self alloc]init];
    p.title=dict[@"title"];
    p.stitle=dict[@"stitle"];
    p.ids=dict[@"ids"];
    p.url=dict[@"url"];
    p.icon=dict[@"icon"];
    p.customUrl=dict[@"customUrl"];
    return p;
}

-(NSArray *)products
{
    if(!_products)
    {
        //1、获取文件路径
        NSString * path=[[NSBundle mainBundle]pathForResource:@"more_project" ofType:@"json"];
        //plist
        //2、转化成临时数组
        //json
        //2、转化成的是NSData
        NSData * data=[NSData dataWithContentsOfFile:path];
        //转化为数组,我们解析的JSON字符串,返回的OC对象可能是字典或者是数组
        NSArray * tempArray=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //options为0就表示不做任何处理,返回的容器也是不可变的
        //    NSJSONReadingMutableContainers = (1UL << 0),//返回的容器可变
        //    NSJSONReadingMutableLeaves = (1UL << 1),叶子可变,也就是返回的如果是字典的话,字典中的值可以是可变的类型。ios7之后没用了
        //    NSJSONReadingAllowFragments = (1UL << 2)允许不是json形式的字符串
        //3、初始化可变的数组
        NSMutableArray * array=[NSMutableArray array];
        //4、遍历临时的数组去获取字典
        for(NSDictionary * dict in tempArray)
        {
            //5、根据字典转模型
            Product * p=[Product productWithDitc:dict];
            //6、把模型添加到可变数组中
            [array addObject:p];
        }
        //7、赋值
        _products=array;
    }
    return _products;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值