JsonKit使用
关于Json解析用的工具,苹果公司提供了原生的解析框架 NSJSONSerialization, 该原生框架的速度是最快的。但有个缺陷是不支持iOS5.0一下版本,所以还是选用第三方框架,第三方框架有很多,具体的选择用的是JsonKit.
因为它速度很快也很好用,关于它和其他的解析工具的对比就不做介绍,目前为止是最好的第三方Json解析工具。
下载JsonKit文件
https://github.com/johnezang/JSONKit
直接把两个文件JsonKit.h JsonKit.m拖到工程中。
好了,可以使用了。如果你遇见报告JsonKit.m文件中的方法找不到
比如:
NSDictionary*deserializedData =[jsonData objectFromJSONString];
-[__NSCFString objectFromJSONString]: unrecognized selector sent to instanceobjectFromJSONString
那是因为工程没有导入进.m 文件
打开工程配置选项
“Build Phases”
added JsonKit.m
//
具体的使用,
贴些代码说明,源代码来自网络:http://blog.csdn.net/ciaos/article/details/7745979
NSString *res = nil; /* * json格式编码 */ //字符串 NSString *str = @"this is a nsstring"; res = [str JSONString]; NSLog(@"res= %@", [NSString stringWithString: res]); //res= "this is a nsstring" //数组 NSArray *arr = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",nil]; res = [arr JSONString]; NSLog(@"res= %@", [NSString stringWithString: res]); [arr release]; //res= ["One","Two","Three"] //字典类型(对象) 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]); //res= {"pets":["dog","cat"],"other":[true,30]} /* * json格式解码 */ JSONDecoder *jd=[[JSONDecoder alloc] init]; //针对NSData数据 NSData *data = [dic JSONData]; NSDictionary *ret = [jd objectWithData: data]; NSLog(@"res= %@", [ret objectForKey:@"pets"]); //res= ( // dog, // cat //) NSLog(@"res= %@", [[ret objectForKey:@"other"] objectAtIndex:0]); //res= 1 //针对NSString字符串数据 NSString *nstr = [dic JSONString]; NSDictionary *ret2 = [jd objectWithUTF8String:(const unsigned char *)[nstr UTF8String] length:(unsigned int)[nstr length]]; NSLog(@"res= %d", [[ret2 objectForKey:@"pets"] indexOfObject:@"cat"]); //res= 1 NSLog(@"res= %@", [[ret2 objectForKey:@"other"] objectAtIndex:1]); //res= 30 [jd release];
浙公网安备 33010602011771号