JSONKit是Object-C一个处理json数据的库,非常高效而且易用,对比同类型的库有非常明显的性能优势,见下图:
JSON和Object-C中数据类型的映射关系如下表所示
JSON | Objective-C |
---|---|
null |
NSNull |
trueandfalse |
NSNumber |
String | NSString |
NSArray | |
NSDictionary |
下面写一个简单的程序使用一下JSONKit(只需下载头文件以及源文件,放在项目目录下)
- #import<Foundation/Foundation.h>
- #import"lib/JSONKit.h"
- intmain(intargc,constchar*argv[]){
- NSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];
- NSString*res=nil;
- /*
- *json格式编码
- */
- //字符串
- NSString*str=@"thisisansstring";
- res=[strJSONString];
- NSLog(@"res=%@",[NSStringstringWithString:res]);
- //res="thisisansstring"
- //数组
- NSArray*arr=[[NSArrayalloc]initWithObjects:@"One",@"Two",@"Three",nil];
- res=[arrJSONString];
- NSLog(@"res=%@",[NSStringstringWithString:res]);
- [arrrelease];
- //res=["One","Two","Three"]
- //字典类型(对象)
- NSArray*arr1=[NSArrayarrayWithObjects:@"dog",@"cat",nil];
- NSArray*arr2=[NSArrayarrayWithObjects:[NSNumbernumberWithBool:YES],[NSNumbernumberWithInt:30],nil];
- NSDictionary*dic=[NSDictionarydictionaryWithObjectsAndKeys:arr1,@"pets",arr2,@"other",nil];
- res=[dicJSONString];
- NSLog(@"res=%@",[NSStringstringWithString:res]);
- //res={"pets":["dog","cat"],"other":[true,30]}
- /*
- *json格式解码
- */
- JSONDecoder*jd=[[JSONDecoderalloc]init];
- //针对NSData数据
- NSData*data=[dicJSONData];
- NSDictionary*ret=[jdobjectWithData:data];
- NSLog(@"res=%@",[retobjectForKey:@"pets"]);
- //res=(
- //dog,
- //cat
- //)
- NSLog(@"res=%@",[[retobjectForKey:@"other"]objectAtIndex:0]);
- //res=1
- //针对NSString字符串数据
- NSString*nstr=[dicJSONString];
- NSDictionary*ret2=[jdobjectWithUTF8String:(constunsignedchar*)[nstrUTF8String]length:(unsignedint)[nstrlength]];
- NSLog(@"res=%d",[[ret2objectForKey:@"pets"]indexOfObject:@"cat"]);
- //res=1
- NSLog(@"res=%@",[[ret2objectForKey:@"other"]objectAtIndex:1]);
- //res=30
- [jdrelease];
- [pooldrain];
- return0;
- }