在项目中与服务器交互的时候,经常要遇到解析json的情况,如果有同学想要解析JSON,那么JSONKit可以是一个不错的选择
首先可以去gitHub上下载JSONKit 地址:JSONKit
放入工程以后,把JSONKit设置为不支持arc的模式
然后在点m修改2个地方
//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"}]
{"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);
源码:JsonKitDemo