JSONKit的使用方法

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

json开源的类库有很多,其中JSONKit库是非常简单易用而且效率又比较高的,重要的JSONKit适用于ios 5.0以下的版本。

下载地址: https://github.com/johnezang/JSONKit

使用JSONKit库来解析json文件,只需要下载JSONKit.h 和JSONKit.m添加到工程中;然后加入libz.dylib即可

解析代码举例:

  1. #import "JSONKit.h"
  2.  
  3. //假设 strJson 是网络上接收到的 json 字符串,
  4. NSString *strJson = @"[{\"Id\": 1,\"BrandName\": \"爱马仕\" },{\"Id\": 2,\"BrandName\": \"安娜苏\"}]";
  5. NSArray *arrlist=[strJson objectFromJSONString];
  6. NSLog(@"%d",[arrlist count]);
  7. for (int i=0; i<[arrlist count]; i++) {
  8. NSDictionary *item=[arrlist objectAtIndex:i];
  9. NSString *BrandName=[item objectForKey:@"BrandName"];
  10. NSLog(@"%@",BrandName);
  11. }

字典arrlist便是解析好的json文件了。

JSONKit库也可以用来生成json文件

代码举例:

  1. NSMutableDictionary *jsonDic = [NSMutableDictionary dictionary];
  2. NSMutableDictionary *alert = [NSMutableDictionary dictionary]
  3. NSMutableDictionary *aps = [NSMutableDictionary dictionary];
  4. [alert setObject:@"a msg come!" forKey:@"body"];
  5. [aps setObject:alert forKey:@"alert"];
  6. [aps setObject:@"3" forKey:@"bage" ];
  7. [aps setObject:@"def.mp3" forKey:@"sound"];
  8. [jsonDic setObject:aps forKey:@"aps"];
  9. NSString *strJson = [jsonDic JSONString];

猜你在找的Json相关文章