1. json的使用场景
网络传递给我们(客户端)的数据都是二进制的,需要我们把二进制的数据转化为json字符串,然后再转换为数组, 字典, 或者自定义的模型对象,这样才方便使用.
2. json解析的发展
iOS 5
中apple增加了解析JSON的API——NSJSONSerialization
.网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。所以,自此以后,解析json的第三方框架逐渐停止更新.- 在iOS中,JSON的常见解析方案有4种
- 第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
- 苹果原生(自带):NSJSONSerialization(性能最好)
3. 怎样使用苹果原生的NSJSONSerialization
对json数据进行解析?
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"连接错误: %@", connectionError);
return;
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
NSError *err;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if (err) {
NSLog(@"解析json出错 %@", err);
return;
}
NSLog(@"%@", jsonObject);
}
}];
}
// 代码运行结果 - 此处解析到的对象是字典类型(无序)
2016-11-09 01:33:47.456 NSJSONSerialization解析json数据[1286:32953] {
message = "\U5403\U996d\U996d,\U7761\U89c9\U89c9,\U4e0a\U8bfe\U8bfe,\U6253\U8c46\U8c46";
messageId = 001;
}