您的位置:首页 > 移动开发 > Swift

iOS(Swift)学习笔记之SwiftyJSON的使用

2020-03-01 20:18 381 查看

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

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
包含
unsupportedType
indexOutOfBounds
elementTooDeep
wrongType
notExist
invalidJSON
errorDomain

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"
]
]

转载于:https://www.cnblogs.com/metaphors/p/9405432.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
aigua1949 发布了0 篇原创文章 · 获赞 0 · 访问量 165 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: