在項目中與伺服器互動的時候,經常要遇到解析json的情況,如果有同學想要解析JSON,那麼JSONKit可以是一個不錯的選擇
首先可以去gitHub上下載JSONKit 地址:JSONKit
放入工程以後,把JSONKit設定為不支援arc的模式
然後在點m修改2個地方<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">//array->isa = _JKArrayClass; object_setClass(array, _JKArrayClass);// dictionary->isa = _JKDictionaryClass; object_setClass(dictionary, _JKDictionaryClass);原因是isa已經被廢棄了,所以請調用object_setClass()和object_getClass()函數來搞定
這裡特別設定了2個json串,供大家參考學習
arr.conf
[{"preview_sub": "adornment_fly_1_100.png", "width": "300", "path": "adornment_fly_1.png", "name": "adornment_fly_1.png", "height": "300"}, {"preview_sub": "adornment_fly_2_100.png", "width": "300", "path": "adornment_fly_2.png", "name": "adornment_fly_2.png", "height": "300"}]
dict.conf
{"status": "ok", "after": "14851", "before": "11011"}
NSString *res = nil; //數組轉json串 NSArray *arr = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",nil]; res = [arr JSONString]; NSLog(@"res= %@", [NSString stringWithString: res]); //字典類型(對象)轉json串 NSArray *arr1 = [NSArray arrayWithObjects:@"dog",@"cat",nil]; NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithInt:30],nil]; NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:arr1,@"pets",arr2,@"other",nil]; res = [dic JSONString]; NSLog(@"res= %@", [NSString stringWithString: res]); //json串轉數組 NSString* arrConf = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"arr" ofType:@"conf"] encoding:NSUTF8StringEncoding error:nil]; NSArray *ConfArr = [arrConf objectFromJSONString]; NSLog(@"%@",ConfArr); //json串轉字典 NSString* dicConf = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dict" ofType:@"conf"] encoding:NSUTF8StringEncoding error:nil]; NSArray *ConfDic = [dicConf objectFromJSONString]; NSLog(@"%@",ConfDic);