本文爲原創文章,轉載請標明出處html
platform :ios, '10.0' target '<Your Target Name>' do use_frameworks! pod 'SwiftyJSON', '~> 4.0.0' end
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) }
// 方式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})
無論JSON是數組類型仍是字典類型key
的類型都爲String
。ios
for (key,subJSON) in json { ... }
枚舉類型SwiftyJSONError
包含unsupportedType
、indexOutOfBounds
、elementTooDeep
、wrongType
、notExist
、invalidJSON
、errorDomain
。json
經過.number
、.string
、.bool
、.int
等方法獲取到的是可選值。swift
if let id = json["user"]["name"].string { ... } else { ... print(json["user"]["name"].error!) }
經過.xxxValue
方法獲取到的是非可選值。數組
// 若不是String或爲nil,返回「」 let name: String = json["name"].stringValue
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]
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") }
// 判斷是否存在 if json["name"].exists()
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)
輸出:code
[ "first_name": "Theo", "last_name": "Tsao", "age": 22, "skills": ["Coding", "Reading", "Writing"], "address": [ "street": "Software St", "zip": "210012", "city": "Nanjing" ] ]