--
layout: blog
title: 'iOS中將Json字符串轉(zhuǎn)為對象'
date: 2017-05-02 12:11:34
categories: blog
tags: code
image: ''
lead-text: 'iOS中Json字符串轉(zhuǎn)為對象'
iOS中將Json字符串轉(zhuǎn)為對象
好久沒寫iOS了荤傲,在轉(zhuǎn)Json的時候就完全忘記了怎么轉(zhuǎn)Json了,所以記錄一下幅骄,貼一段以前寫的代碼
*.h文件中聲明兩個方法拦惋,用來將Json字典轉(zhuǎn)換為對象-簡單對象气破,對象中不包含list等復(fù)雜數(shù)據(jù)結(jié)構(gòu)且不包含子類</br>
/* *.h文件皇帮,創(chuàng)建兩個方法,將傳入的字典返回為對象 */
@interface SearchHotWord : NSObject
@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger wordId;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)searchHotWordWithDict:(NSDictionary *)dict;
@end
/* *.m文件昂灵,使用kvo設(shè)置對應(yīng)的對象和dict中的value值舱禽,注意的是這里</br>如果key的值和dict中的key不一樣炒刁,那么需要在forUndefinedKey方法中將</br>對應(yīng)的key進行關(guān)聯(lián) */
@implementation SearchHotWord
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+ (instancetype)searchHotWordWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
if ([key isEqualToString:@"id"]) {
_wordId = [value integerValue];
}
}
//- (void)setValue:(id)value forUndefinedKey:(NSString *)key
//{
// if ([key isEqualToString:@"id"]) { // id重名,用這個方法避免
// _wordId = value;
// }
//}
@end
復(fù)雜對象轉(zhuǎn)換誊稚,包含list等復(fù)雜結(jié)構(gòu)和子類對象翔始,使用mj的轉(zhuǎn)換方式
/* *.h文件,有兩個復(fù)雜對象片吊,其中一個是一個可變array中包含一個對象*/
@property (nonatomic, strong) SingerInfo *singerinfo;
@property (nonatomic, assign) NSInteger songcount;
@property (nonatomic, strong) NSMutableArray<SearchSong *> *songlist;
/* *.m文件绽昏,使用mj的引用對對象進行解釋,只需要對可變array中的對象進行解釋,其他的非嵌套對象不需要*/
+ (NSDictionary *)mj_objectClassInArray{
return @{
@"songlist" : @"SearchSong"
};
}