将JSONKit.h和JSONKit.m拖到项目中
下载地址:https://github.com/johnezang/JSONKit/
配置:
//导入JSONKit时候需要特别的配置 (-fno-objc-arc)
//(1)修改JSONKit.m文件第680行,修改为object_setClass(array, _JKArrayClass);
//(2)修改JSONKit.m文件第931行,修改为object_setClass(dictionary, _JKDictionaryClass);
下面代码:
//string to dictionary
NSString *resultStr = @"{"name": "admin","list": ["one","two","three"]}";
NSData* jsonData = [resultStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *resultDict = [jsonData objectFromJSONData];
NSLog(@"name is :%@",[resultDict objectForKey:@"name"]);
NSArray *list = [resultDict objectForKey:@"list"];
for (NSString *str in list) {
NSLog(@"list res:%@",str);
}
//dicttionary to string
NSString *jsonStr = [resultDict JSONString];
NSLog(@"temp is :%@",jsonStr);
为了方便大家看懂在上面的代码中做了相应更改。
//创建或者读取json数据
NSString *resultStr = @"{"name": "admin","list": ["one","two","three"]}";
//编码json数据
NSData* jsonData = [resultStr dataUsingEncoding:NSUTF8StringEncoding];
//开始解析json数据
NSDictionary *resultDict = [jsonData objectFromJSONData];
//读取解析后的json数据放熬数组里面
NSArray *arr = [resultDict objectForKey:@"name"];
NSArray *list = [resultDict objectForKey:@"list"];
NSLog(@"arr is :%@\n, list is :%@", arr,list);
//将解析后json数据再转换为json进行输出,
NSString *jsonStr = [resultDict JSONString];
NSLog(@"temp is :%@",jsonStr);
到这里我们就为json解析中的jsonKit做了简单的介绍,如果以后你还遇到需要解析json为妾是要用jsonKit的时候,基本上只要把上面的代码弄懂了,再在你项目里面做小部分的相应更改就能很好的操作了!
下面是解析json的一个很好的实例
- (IBAction)btnPressJsonKit:(id)sender {
//如果json是“单层”的,即value都是字符串、数字,可以使用objectFromJSONString
NSString *json1 = @"{"a":123, "b":"abc"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
[json1 release];
//如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能会报错(测试结果表明:使用由网络或得到的php/json_encode生成的json时会报错,但使用NSString定义的json字符串时,解析成功),最好使用objectFromJSONStringWithParseOptions:
NSString *json2 = @"{"a":123, "b":"abc", "c":[456, "hello"], "d":{"name":"张三", "age":"32"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
[json2 release];
}