iOS-jason解析的方法:解析库

在作项目的时候免不了要解析网络数据,XML 和 JSon 格式html

这篇文章探讨解析JSon数据:ios

JSon解析库:
git

一、NSJSONSerialization (苹果 PAI)github

二、JSONKit json

三、NextiveJson网络

四、YAJLapp

五、SBJSON  (json-framework)spa

六、TouchJSONcode

速度比较:htm

大部分人用SBJSon,可是五、6的速度最慢,  一、2的速度最快。

使用详解:

一、NSJSONSerialization

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/index.html

解析json数据为 NSDictionary、NSArray :

NSData *data = dataes;//网络解析到dataes
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//再从字典中获取各类数据

封装 NSDictionary 、 NSArray 为json数据:

NSDictionary *dic;  
if ([NSJSONSerialization isValidJSONObject:dic]){  
    //isValidJSONObject 判断对象是否能够构建成json对象 
    NSError *error;  
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];  
    //NSJSONWritingPrettyPrinted 把json数据格式化,不然会在一行中显示。更有可读性。  
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];  
}


二、JSONKit 

https://github.com/johnezang/JSONKit

#import "JSONKit.h"    (没有使用ARC   添加  -fno-objc-arc) 

解析json数据为 NSDictionary、NSArray :

NSData *data = dataes;//网络解析到dataes
NSDictionary *dic = [data  objectFromJSONData];

封装 NSDictionary 、 NSArray 为json数据:

NSDictionary *dic;
NSString *strJson = [dic JSONString];


五、SBJSON

http://stig.github.com/json-framework/

解析json数据为 NSDictionary、NSArray :

NSDictionary *dic;
SBJsonWriter *json = [[SBJsonWriter alloc] init];  
NSString *str = [json stringWithObject:dic];

封装 NSDictionary 、 NSArray 为json数据:

NSData *datas;
NSString * str = [[NSString alloc] initWithData: datas encoding:NSUTF8StringEncoding]; 
NSDictionary *dic = [[[SBJsonParser alloc] init] objectWithString:str];
相关文章
相关标签/搜索