本文为原创文章,转载请标明出处

1. 通过CocoaPods安装SwiftyJSON

platform :ios, '10.0'

target '<Your Target Name>' do

  use_frameworks!

  pod 'SwiftyJSON', '~> 4.0.0'

end

2. 初始化

import SwiftyJSON

let json = JSON(data: dataFromNetworking)
let json = JSON(jsonObject)
if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}

3. 下标访问

// 方式1
let name = json[1]["list"][2]["name"].string //方式2
let name = json[1,"list",2,"name"].string //方式3
let keys:[JSONSubscriptType] = [1,"list",2,"name"]
let name = json[keys].string
let arrayNames =  json["users"].arrayValue.map({$0["name"].stringValue})

4. 循环遍历

不管JSON是数组类型还是字典类型key的类型都为String

for (key,subJSON) in json {
...
}

5. 错误处理

枚举类型SwiftyJSONError包含unsupportedTypeindexOutOfBoundselementTooDeepwrongTypenotExistinvalidJSONerrorDomain

6. 可选值获取

通过.number.string.bool.int等方法获取到的是可选值。

if let id = json["user"]["name"].string {
...
} else {
...
print(json["user"]["name"].error!)
}

7. 非可选值获取

通过.xxxValue方法获取到的是非可选值。

// 若不是String或为nil,返回“”
let name: String = json["name"].stringValue

8. 设置值

json["name"] = JSON("new-name")
json[0] = JSON(1)
json["name"].string =  "Jack"
json.arrayObject = [1,2,3,4]
json.dictionaryObject = ["name":"Jack", "age":25]

9. 原始数据

let rawObject: Any = json.object
let rawValue: Any = json.rawValue
do {
let rawData = try json.rawData()
} catch {
print("Error \(error)")
}
if let rawString = json.rawString() {
...
} else {
print("json.rawString is nil")
}

10. 其他方法

exists

// 判断是否存在
if json["name"].exists()

merge

let original: JSON = [
"first_name": "Theo",
"age": 20,
"skills": ["Coding", "Reading"],
"address": [
"street": "Software St",
"zip": "210046",
]
] let update: JSON = [
"last_name": "Tsao",
"age": 22,
"skills": ["Writing"],
"address": [
"zip": "210012",
"city": "Nanjing"
]
] let updated = original.merge(with: update)

输出:

[
"first_name": "Theo",
"last_name": "Tsao",
"age": 22,
"skills": ["Coding", "Reading", "Writing"],
"address": [
"street": "Software St",
"zip": "210012",
"city": "Nanjing"
]
]

最新文章

  1. erlang 虚机性能调优
  2. Unicode字符集下CString与char *转换 (解决中文乱码等)(转)
  3. Visual Studio 2015速递(1)——C#6.0新特性怎么用
  4. 【背景建模】SOBS
  5. 玩了一天的Git
  6. no-jquery 01Elements
  7. Laravel No such file or directory in /bootstrap/autoload.php on line 17
  8. [转载]node.js express 4.x 安装指南,没有自动配置环境变量的问题
  9. iOS开发关于AppStore程序的上传流程
  10. Robotium调用getActivity()导致程序挂起的方法
  11. 5_find grep sed awk 详解
  12. HashMap 数组应用面试题(Point)
  13. 第三章之S5PV210串口初始化
  14. Entitas Learning Document
  15. 【English EMail】Compensation Planning Memo
  16. Jquery 数组操作大全【转载】
  17. idea 中dao层自动生成接口
  18. vue安装,router-link的一些属性,用法,tag active-class,to,replace,exex等等
  19. git删除仓库的某个文件
  20. 2018.11.24 poj2774Long Long Message(后缀数组)

热门文章

  1. Python笔记_第四篇_高阶编程_检测_2.对类进行单元检测
  2. Nginx模块-ngx_http_mirror_module-流量复制【转】
  3. 【@ConfigurationProperties注解】Not Found The requested URL /spring-boot/docs/2.2.2.RELEASE/reference/html/configuration-metadata.html was not found on this server.
  4. spring-boot 如何加载rsources下面的自定义配置文件
  5. PAT Advanced A1104 Sum of Number Segments (20) [数学问题]
  6. 你需要了解的JIT Debugging
  7. WIFI无线协议802.11a/b/g/n/ac的演变以及区别
  8. Popular generalized linear models|GLMM| Zero-truncated Models|Zero-Inflated Models|matched case–control studies|多重logistics回归|ordered logistics regression
  9. 洛谷 P3811 【模板】乘法逆元(欧拉定理&amp;&amp;线性求逆元)
  10. Spring的设计理念和整体架构