JSONKit 使用示例

前端之家收集整理的这篇文章主要介绍了JSONKit 使用示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JSONKit是Object-C一个处理json数据的库,非常高效而且易用,对比同类型的库有非常明显的性能优势,见下图:


JSON和Object-C中数据类型的映射关系如下表所示

@H_404_15@

NumberArrayObject
JSON Objective-C
@H_404_36@null NSNull
trueandfalse NSNumber
String NSString
NSArray
NSDictionary

下面写一个简单的程序使用一下JSONKit(只需下载头文件以及源文件,放在项目目录下

  1. #import<Foundation/Foundation.h>
  2. #import"lib/JSONKit.h"
  3. intmain(intargc,constchar*argv[]){
  4. NSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];
  5. NSString*res=nil;
  6. /*
  7. *json格式编码
  8. */
  9. //字符串
  10. NSString*str=@"thisisansstring";
  11. res=[strJSONString];
  12. NSLog(@"res=%@",[NSStringstringWithString:res]);
  13. //res="thisisansstring"
  14. //数组
  15. NSArray*arr=[[NSArrayalloc]initWithObjects:@"One",@"Two",@"Three",nil];
  16. res=[arrJSONString];
  17. NSLog(@"res=%@",[NSStringstringWithString:res]);
  18. [arrrelease];
  19. //res=["One","Two","Three"]
  20. //字典类型(对象)
  21. NSArray*arr1=[NSArrayarrayWithObjects:@"dog",@"cat",nil];
  22. NSArray*arr2=[NSArrayarrayWithObjects:[NSNumbernumberWithBool:YES],[NSNumbernumberWithInt:30],nil];
  23. NSDictionary*dic=[NSDictionarydictionaryWithObjectsAndKeys:arr1,@"pets",arr2,@"other",nil];
  24. res=[dicJSONString];
  25. NSLog(@"res=%@",[NSStringstringWithString:res]);
  26. //res={"pets":["dog","cat"],"other":[true,30]}
  27. /*
  28. *json格式解码
  29. */
  30. JSONDecoder*jd=[[JSONDecoderalloc]init];
  31. //针对NSData数据
  32. NSData*data=[dicJSONData];
  33. NSDictionary*ret=[jdobjectWithData:data];
  34. NSLog(@"res=%@",[retobjectForKey:@"pets"]);
  35. //res=(
  36. //dog,
  37. //cat
  38. //)
  39. NSLog(@"res=%@",[[retobjectForKey:@"other"]objectAtIndex:0]);
  40. //res=1
  41. //针对NSString字符串数据
  42. NSString*nstr=[dicJSONString];
  43. NSDictionary*ret2=[jdobjectWithUTF8String:(constunsignedchar*)[nstrUTF8String]length:(unsignedint)[nstrlength]];
  44. NSLog(@"res=%d",[[ret2objectForKey:@"pets"]indexOfObject:@"cat"]);
  45. //res=1
  46. NSLog(@"res=%@",[[ret2objectForKey:@"other"]objectAtIndex:1]);
  47. //res=30
  48. [jdrelease];
  49. [pooldrain];
  50. return0;
  51. }
JSONKit的接口中还可以自行定制序列化和反序列化选项 原文链接:https://www.f2er.com/json/289988.html

猜你在找的Json相关文章