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的类:

 

JSONObjective-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参数。

 

 
 
 



posted @ 2013-06-20 15:48  shangdahao  阅读(10106)  评论(0编辑  收藏  举报