iOS中將後台JSON資料轉化為模型的總結

來源:互聯網
上載者:User

標籤:

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);

這個時候就可以直接轉為模型了

iOS中將後台JSON資料轉化為模型的總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.