標籤:
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資料轉化為模型的總結