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