iOS Swift-Json解析
来源:互联网 发布:人工智能 创投 编辑:程序博客网 时间:2024/05/22 17:48
在OC中解析json数据我一般用iOS5之后自带的NSJSONSerialization,转为字典或数组再取值。
在Swift中,因为Swift强调类型安全,属性上多了可选类型(optional),使用NSJSONSerialization获取jsonObject后,需要繁琐地downcast,SwiftJson的一个例子
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)if let statusesArray = jsonObject as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ if let user = aStatus["user"] as? NSDictionary{ if let userName = user["name"] as? NSDictionary{ //Finally We Got The Name } } }}
或者可选链式调用
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{ //What A disaster above}
解决办法:SwiftJson https://github.com/pvwoods/SwiftyJSON
let json = JSONValue(dataFromNetworking)if let userName = json[0]["user"]["name"].string{ //Now you got your value}
let json = JSONValue(dataFromNetworking)if let userName = json[999999]["wrong_key"]["wrong_name"].string{ //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety}
SwiftJson是一个枚举类型,内部也是使用NSJSONSerialization解析,当使用key来获取一个json对象,如果获取失败就返回JInvalid,直到最后调用.string .number .bool拆包才返回nil,就算中间获取出错也不会crash。
0 0
- iOS Swift-Json解析
- iOS Json解析Swift
- IOS学习--- Swift JSON解析
- iOS开发之Swift 4 JSON 解析指南
- Swift-解析JSON数据(天气)
- swift 解析json数据
- Swift解析JSON数据
- 使用swift解析json
- Swift 解析 JSON
- swift的json解析
- ios swift http json
- [iOS]#Swift#可选解析-optional
- swift 网络请求&json解析
- swift基础之json解析
- Swift-->Json解析(原生NSJSONSerialization)
- 使用 Swift 进行 JSON 解析
- Swift Json 解析异常处理
- Swift 4 JSON 解析指南
- Fragment里面的Viewpaper不显示内容不执行getItem的解决方案
- 创建交互式博客——jquery (4)
- Interview and English(2)
- HDU 2612 Find a way(双BFS)
- CC3.2+Lua(9) ——从C++过渡到Lua
- iOS Swift-Json解析
- ICD Tools 设计手稿:02 - ICD设计工具基本功能
- 先占一篇
- 数据结构:C++链表类及一元多项式的实现时遇到的困难
- [LinkedIn]Serialize (encode) and deserialize(decode) a binary tree
- QSortFilterProxyModel
- android动态加载(二)
- C# winform或控制台Properties.Settings.Default的使用及存储位置
- 微信菜单定义小工具