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參數。

 

 
 
 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM