zoukankan      html  css  js  c++  java
  • iOS中将后台JSON数据转化为模型的总结

    1.

    再拿到了Json数据后怎么把字典写到数组里面去呢?

      方法1:用最原始的方法  

      

    -(instancetype)initWithDict:(NSDictionary *)dict {

        if(self = [super init]) {

            [self setValuesForKeysWithDictionary:dict];

        }

        return self;

    }

    +(instancetype)modelWithDict:(NSDictionary *)dict {

        return [[self alloc] initWithDict:dict];

    }

    //这个方法一定要写上  ,不然就回报警告的,什么警告呢? undefiedforKey

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

    {

        

    }

    这行代码的作用就是为了避免在你的json'数据的字典在很多个的情况下  然后呢你的.h文件里面可能只有几个字段 而并没有吧json数据里面的全部字段用上的时候这个时候这个就起作用了,这行代码的就可以把多余的字段因为没有一一的键值对应给忽略了

    比如这个时候json数据的层级结构是这样的

    {
      "result": true, 
      "page": 1, 
      "totalPage": 1, 
      "dicMap": {}, 
      "varList": [
        {}, 
        {}
      ]
    }

    //

      你可以这样去解析数据

        NSArray *data  = dict[@"varList"];

            

            for(NSDictionary *dict3 in data) {

                ZYGuess *guess = [ZYGuess modelWithDict:dict3];

                NSLog(@" -----==%@=========",guess);

            }

    方法2,使用JSONModel框架   

    使用说明 :

     这个是我建立的模型层次结构

    #import "JSONModel.h"

    #import "ZYCarouselList.h"

    #import "ZYSpecialList.h"

    #import "ZYHotSaleList.h"

    #import "ZYGuessList.h"

    @interface ZYHomeModel : JSONModel

    @property (nonatomic,strong) ZYCarouselList *carousel;

    @property (nonatomic,strong) ZYSpecialList *special;

    @property (nonatomic,strong) ZYHotSaleList *sale;

    @property (nonatomic,strong) ZYGuessList *guess;

     关键就在这个地方出错了,因为他们这个json数据它们是没有并列的层级关系、

    我现在拿到的json数据只是一个接口的数据 

    @property (nonatomic,strong) ZYCarouselList *carousel;

    @property (nonatomic,strong) ZYSpecialList *special;

    @property (nonatomic,strong) ZYHotSaleList *sale;

    和着3个没有一点的关系

    层级结构错了   所以打印出来的模型一直为null

          ZYGuessList *model = [[ZYGuessList alloc]initWithDictionary:dict error:NULL];

            NSLog(@"%@",model);

    这个时候就可以直接转为模型了

  • 相关阅读:
    不死神兔
    C/C++内存管理详解
    python下调用不在环境变量中的firefox
    【转至nmap】nc命令
    Linux SSH隧道技术(端口转发,socket代理)
    linux共享上网设置
    HDU
    CSU
    HDU
    HDU
  • 原文地址:https://www.cnblogs.com/Ninesday/p/5216264.html
Copyright © 2011-2022 走看看