Swift - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)
2024-08-26 18:02:04
一,使用自带的NSJSONSerialization
苹果从IOS5.0后推出了SDK自带的JSON解决方案NSJSONSerialization,这是一个非常好用的JSON生成和解析工具,效率也比其他第三方开源项目高。
NSJSONSerialization能将JSON转换成Foundation对象,也能将Foundation对象转换成JSON,但转换成JSON的对象必须具有如下属性:
1,顶层对象必须是NSArray或者NSDictionary
2,所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例
3,所有NSDictionary的key必须是NSString类型
4,数字对象不能是非数值或无穷
注意:尽量使用NSJSONSerialization.isValidJSONObject先判断能否转换成功。
样例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var label: UILabel = UILabel (frame: CGRectMake (100, 100,300,100)); label.text = "输出结果在控制台" self .view.addSubview(label) //测试结果在output终端输入,也可以建个命令行应用测试就可以了 testJson() } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //测试json func testJson() { //Swift对象 let user = [ "uname" : "张三" , "tel" : [ "mobile" : "138" , "home" : "010" ] ] //首先判断能不能转换 if (! NSJSONSerialization .isValidJSONObject(user)) { println ( "is not a valid json object" ) return } //利用OC的json库转换成OC的NSData, //如果设置options为NSJSONWritingOptions.PrettyPrinted,则打印格式更好阅读 let data : NSData ! = NSJSONSerialization .dataWithJSONObject(user, options: nil , error: nil ) //NSData转换成NSString打印输出 let str = NSString (data:data, encoding: NSUTF8StringEncoding ) //输出json字符串 println ( "Json Str:" ); println (str) //把NSData对象转换回JSON对象 let json : AnyObject ! = NSJSONSerialization . JSONObjectWithData (data, options: NSJSONReadingOptions . AllowFragments , error: nil ) println ( "Json Object:" ); println (json) //验证JSON对象可用性 let uname : AnyObject = json.objectForKey( "uname" )! let mobile : AnyObject = json.objectForKey( "tel" )!.objectForKey( "mobile" )! println ( "get Json Object:" ); println ( "uname: \(uname), mobile: \(mobile)" ) } } |
输出结果如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
Json Str: Optional({ "uname" : "张三" , "tel" :{ "home" : "010" , "mobile" : "138" }}) Json Object : { tel = { home = 010 ; mobile = 138 ; }; uname = "\U5f20\U4e09" ; } get Json Object : uname: 张三, mobile: 138 |
二,使用第三方库 - JSONKit
1,新建桥街头文件Bridging-Header.h,并设置到编译参数里
1
|
# include "JSONKit.h" |
2,将JSONKit的库文件导入到项目中来(JSONKit.h和JSONKit.m)
3,这时编译会发现报错,这是由于JSONKit库不支持Objective-C的自动引用计数功能导致。
需要在Build Phases -> Compile Sources -> JSONKit.m,双击添加Comipler Flag:-fno-objc-arc 。这样就完成了不支持自动引用计数的配置。
测试代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. testJson() } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func testJson() { //Swift 字典对象 let user = [ "uname" : "user1" , "tel" : [ "mobile" : "138" , "home" : "010" ] ] //使用 JSONKit 转换成为 JSON 字符串 var jsonstring = (user as NSDictionary ). JSONString () println (jsonstring); //由字符串反解析回字典 println (jsonstring.objectFromJSONString() as NSDictionary ) //使用 JSONKit 转换成为 NSData 类型的 JSON 数据 var jsondata = (user as NSDictionary ). JSONData () println (jsondata); //由NSData 反解析回为字典 println (jsondata.objectFromJSONData() as NSDictionary ) } } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
{ "uname" : "user1" , "tel" :{ "home" : "010" , "mobile" : "138" }} { tel = { home = 010 ; mobile = 138 ; }; uname = user1; } <7b22756e 616d6522 3a227573 65723122 2c227465 6c223a7b 22686f6d 65223a22 30313022 2c226d6f 62696c65 223a2231 3338227d 7d> { tel = { home = 010 ; mobile = 138 ; }; uname = user1; } |
最新文章
- java spring mvc restful 上传文件
- 【Cocos2d-x游戏开发】细数Cocos2d-x开发中那些常用的C++11知识
- 打开office word excel弹出visual studio 2008
- 分布式缓存之 memcache 实现分布式缓存
- c#.net对excel的操作——创建一个excel报表两个sheet就是2个表分别添加内容
- Android性能之启动时间篇
- 分布式系统唯一ID生成方案汇总
- CSS引入外部字体
- selenium执行js报错
- HDU-1114(背包DP)
- scala io,ubuntu常见配置
- windows下spark开发环境配置
- [git] git怎样fork一个repo
- iptables防火墙的原理及应用
- termios.h(FreeBSD 12.0)
- HTML代码转换为JavaScript字符串
- SVN启停脚本
- Python Socket实现简单的聊天室
- 139.00.004 Git学习-远程仓库之Github
- (六)SSO之CAS框架扩展 改动CAS源代码实现与ESS动态password验证对接
热门文章
- Poj 3246 Balanced Lineup(线段树基础)
- 管理tips
- BZOJ 1537: [POI2005]Aut- The Bus(dp + BIT)
- [转]VMware 出现下述错误: Application failure. hr=0x80040101:Failed to initialize virtual machine.
- Windows Store Javascript项目使用高德地图、谷歌地图、百度地图API
- jsp页面格式化数字或时间
- 更好地认知Azure
- mysql中IN和EXITS效率
- Java的位运算符具体解释实例——与(&;amp;)、非(~)、或(|)、异或(^)
- PHP - 代码分离