本文目录一览:
iOS中JSON数据的解析
NSJSONSerialization
提供了JSON数据封包、JSON数据解析,NSJSONSerialization
将JSON数据转换为 NSDictionary
或 NSArray
解包方法,将 NSDictionary
、NSArray
对象转换为 JSON 数据(可以通过调用 isValidJSONObject
来判断 NSDictionary
、NSArray
对象是否可以转换为 JSON 数据)封包。
NSJSONSerialization Class Reference
ios开发中,带小括号的JSON怎么解析
使用 IOS5 自带解析类 NSJSONSerialization
方法解析:(无需导入包,IOS5 支持,低版本 IOS 不支持)
- (void)btnPressIOS5Json:(id)sender {
NSError *error;
// 加载一个NSURL对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
// 将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
NSString *detail = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],
[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"],[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]];
NSLog(@"%@",detail);
NSLog(@"weatherInfo字典里面的内容为--》%@", weatherDic );
}
在ios中json数据怎么解析
刚刚下午那会弄了个解析 xml demo 的小例子,本想着 json 也挺复杂,弄还是不弄,但是简单的看了下发现挺简单。
考虑了很久,还是写上来吧,毕竟 json 用得太多了,而且算是自己的积累吧,毕竟刚开始学习 IOS 开发方面的知识,就当是巩固了撒!
还是先看个效果图吧,如下!
接下来看下工程目录吧,其实并没有必要,直接建立一个工程就行,算了,还是贴上来吧,如下:
工程目录中有个 Notes.json
文件,该文件就是 要解析的 json 数据了,也截下图吧,如下:
OK,以上准备完毕,就开始编码了,在此之前故事版的内容就和我上篇博客文章《IOS 解析 xml 故事版》是一样配置的,这里就不啰嗦了。首先看下 chonViewController.h
文件,代码如下:
//
// chonViewController.h
// TestJson
//
// Created by choni on 14-5-16.
// Copyright (c) 2014年 choni. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface chonViewController : UITableViewController
// 保存数据列表
@property(nonatomic,strong) NSMutableArray * listData;
@end
与之对应的 chonViewController.m
文件代码如下:
//
// chonViewController.m
// TestJson
//
// Created by choni on 14-5-16.
// Copyright (c) 2014年 choni. All rights reserved.
//
#import "chonViewController.h"
@interface chonViewController ()
@end
@implementation chonViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * path = [[NSBundle mainBundle] pathForResource:@"Notes" ofType:@"json"];
NSData * jsonData = [[NSData alloc] initWithContentsOfFile:path];
NSError * error;
id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:error];
if (!jsonObj || error) {
NSLog(@"JSON解析失败");
}
self.listData = [jsonObj objectForKey:@"Record"];
}
#pragma mark - tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.listData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSMutableDictionary * dict = self.listData[indexPath.row];
cell.textLabel.text = [dict objectForKey:@"Content"];
cell.detailTextLabel.text = [dict objectForKey:@"CDate"];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
OK,现在就可以编译运行的程序了,但是有个主意的地方:
- 因为使用
NSJSONSerialization
实现 JSON 解码,要确定你的项目使用 IOS 5 SDK 才可以。 - 其他的就没有什么了,介绍下
NSJSONSerialization
的类方法吧:
- NSJSONReadingMutableContainers:指定解析返回的是可变的数组或字典,这个方法还是比较实用的,因为如果 JSON 数据需要改,不用管。
- NSJSONReadingMutableLeaves:指定叶节点是可变的字符串。
- NSJSONReadingAllowFragments:指定顶级节点可以部署数组或字典。
iOS开源JSON解析库MJExtension
iOS 中 JSON 与 NSObject 互转有两种方式:
- iOS 自带类
NSJSONSerialization
- 第三方开源库 SBJSON、JSONKit、MJExtension 项目中一直用 MJExtension 来进行 JSON 与 Model 的互转,非常方便、强大,接下来介绍一下这个轻量、强大的开源库。
1. 什么是 MJExtension?
MJExtension 是一套字典和模型之间互相转换的轻量级开源框架,GitHub 地址为:GitHub - CoderMJLee/MJExtension。功能如下:
2. MJExtension 架构
- UML 类图
- 类介绍
3. MJExtension JSON 转 Model 流程图
4. MJExtension 用法举例
关于用法详情请见:GitHub - CoderMJLee/MJExtension。我这里只介绍两种常用的用法:JSON 转 Model,JSON 转 Model 数组。
怎么生成和解析iOS开发JSON格式数据
导语:JSON 作为数据包格式传输的时候具有更高的效率,这是因为 JSON 不像 XML 那样需要有严格的闭合标签,这就让有效数据量与总数据包比大大提升,从而减少同等数据流量的情况下,网络的传输压力。JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是 JavaScript 很容易解释它,而且 JSON 可以表示比“名称 / 值对”更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。
一、如何生成 JSON 格式的数据?
1. 利用字典 NSDictionary
转换为键/值格式的数据。
NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
// 1. 判断当前对象是否能够转换成 JSON 数据
BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
if (isYes) {
NSLog(@"可以转换");
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
[jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"JSON数据生成失败,请检查数据格式");
}
2. 通过 JSON 序列化可以转换数组,但转换结果不是标准化的 JSON 格式。
NSArray *array = @[@"qn", @18, @"ya", @"wj"];
BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
if (isYes) {
NSLog(@"可以转换");
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
[data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
} else {
NSLog(@"JSON数据生成失败,请检查数据格式");
}
二、如何解析 JSON 格式的数据?
1. 使用 TouchJSon 解析方法(需导入包:#import "TouchJson/JSON/CJSONDeserializer.h"
)
// 使用 TouchJson 来解析北京的天气
NSURL *url = [NSURL URLWithString:@""];
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:error];
NSLog(@"jsonString---%@",jsonString);
// 将解析得到的内容存放字典中,编码格式为UTF8,防止取值的时候发生乱码
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:error];
// 因为返回的 Json 文件有两层,去第二层内容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo---%@",weatherInfo);
// 取值打印
NSLog(@"%@",[NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
2. 使用 SBJson 解析方法(需导入包:#import "SBJson/SBJson.h"
)
// 使用 SBJson 解析北京的天气
NSURL *url = [NSURL URLWithString:@""];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"%@", [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
3. 使用 IOS5 自带解析类 NSJSONSerialization
方法解析(无需导入包,IOS5 支持,低版本 IOS 不支持)
// 从中国天气预报网请求数据
NSURL *url = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data && !error) {
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSDictionary *dict = obj[@"weatherinfo"];
NSLog(@"%@---%@", dict, dict[@"city"]);
}
}] resume];
4. 使用 JSONKit 的解析方法(需导入包:#import "JSONKit/JSONKit.h"
)
// 如果 json 是“单层”的,即 value 都是字符串、数字,可以使用 objectFromJSONString
NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
// 如果 json 有嵌套,即 value 里有 array、object,如果再使用 objectFromJSONString,程序可能会报错(测试结果表明:使用由网络或得到的 php/json_encode 生成的 json 时会报错,但使用 NSString 定义的 json 字符串时,解析成功),最好使用 objectFromJSONStringWithParseOptions:
NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"张三\", \"age\":\"32\"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);