iOS开源项目:JSONKit

一个Json解析库,其特点是代码简单,只有一个.h和.m文件。

https://github.com/johnezang/JSONKit

 JSON(JavaScript Object Notation)是一个轻量级的,基于文本的,序列结构化数据格式. 由RFC 4627定义.提供以下主要类型:

null
Boolean true and false
Number
String
Array
Object (a.k.a. Associative Arrays, Key / Value Hash Tables, Maps, Dictionaries, etc.)

对应的Objective—C的类:

 

JSON Objective-C
null NSNull
true and false NSNumber
Number NSNumber
String NSString
Array NSArray
Object NSDictionary

1、使用:

复制代码
NSString *jsonstring =@"[{\"age\":18,\"book\":{\"price\":23.2,\"title\":\"boook111\"},\"name\":\"samyou\"},{\"age\":22,\"book\":{\"price\":33,\"title\":\"booook222\"},\"name\":\"samsam\"}]";  
  
    NSData *data=[jsonstring dataUsingEncoding:NSUTF8StringEncoding];  
  
    NSArray *arr=(NSArray *)[data mutableObjectFromJSONData];  
  
    NSLog(@"count=%d",arr.count);  
  
    for(int i=0;i<arr.count;i++)  
  
    {  
  
        NSDictionary *people=[arr objectAtIndex:i];  
  
        NSString *name=[people objectForKey:@"name"];  
  
        NSString *age=[people objectForKey:@"age"];  
  
        NSLog(@"person withname=%@,age=%d",name,[age intValue]);  
  
        NSDictionary *book=[people objectForKey:@"book"];  
  
        NSString *bookname=[book objectForKey:@"title"];  
  
        NSNumber *price=[book objectForKey:@"price"];  
  
        NSLog(@"book with title=%@,price=%f",bookname,[price doubleValue]);  
  
    }  
复制代码

使用上很简单,利用字典键值对获取就行,参考http://stephen830.iteye.com/blog/1718550。

2、原理:
JSONKit的源码只有个两个文件,先看看解析JSON的流程。

    NSArray *arr=(NSArray *)[data mutableObjectFromJSONData];

这个方法是NSData的Category,里面调用了

JSONDecoder的解析方法:

[JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error];

总的来说,JSONKit对

NSArray

NSString

NSData

NSDictionary

都进行了序列化和反序列化的扩展,可以把这些对象与JSON对象之间相互转换。

由于JSONKit没有使用ARC,所以使用时不要忘了build phases -compile sources 选择文件后面加-fno-objc-arc参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值