json解析的四种方法

来源:互联网 发布:汽车租赁源码 编辑:程序博客网 时间:2024/06/07 04:54

参考:http://blog.csdn.net/enuola/article/details/7903632

JSON解析主要有四种方法:TouchJson、SBJson、JSONKit和iOS原生的方法

touchJson下载包:

SBJson下载包:https://github.com/stig/json-framework

JSONKit下载包:https://github.com/johnezang/JSONKit

TouchJson解析

导入#import "TouchJson/JSON/CJSONDeserializer.h"

NSURL *url = [NSURL URLWithString:@""];

NSError *error;

NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

NSLog(@"jsonString-->%@",jsonString);

NSDictionary *rootDic =[ [CJSONDeserializer deserializer]deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];


SBJson解析

导入#import "SBJson/SBJson.h

NSURL *url = [NSURL URLWithString:@""];

NSError *error = nil;

NSString *jsonString = [NSString stringWithContentOfURL:url encoding:NSUTF8StringEncoding error:&error];

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];

JSONKit解析

导入#import "JSONKit/JSONKit.h"

如果json是单层的,即value是字符、数字,可以用objectFromJSONString

NSString *json = @"{\"a\":123,\"b\":\"abc\"}";

NSDictionary *data = [json objectFromJSONString];

如果json有嵌套,即value里有array、object,如果再用objectFromJSONString,程序可能报错,最好使用objectFromJSONStringWithParseOptions:

NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"张三\", \"age\":\"32\"}}";

NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];

iOS自带解析类

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:bill error:nil];

NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];



0 0
原创粉丝点击