This is an original article, please mark it for reprinting Source
1. Install SwiftyJSON via CocoaPods
platform :ios, '10.0' target '<Your Target Name>' do use_frameworks! pod 'SwiftyJSON', '~> 4.0.0' end
2. Initialization
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. Subscript Access
// Mode 1 let name = json[1]["list"][2]["name"].string //Mode 2 let name = json[1,"list",2,"name"].string //Mode 3 let keys:[JSONSubscriptType] = [1,"list",2,"name"] let name = json[keys].string
let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
4. Loop traversal
Whether the JSON is an array type or a dictionary type key is a String.
for (key,subJSON) in json { ... }
5. Error handling
The enumeration type SwiftyJSONError contains unsupportedType, indexOutOfBounds, elementTooDeep, wrongType, notExist, invalidJSON, errorDomain.
6. Optional value acquisition
Optional values are obtained from.number,.string,.bool,.int, and so on.
if let id = json["user"]["name"].string { ... } else { ... print(json["user"]["name"].error!) }
7. Non-optional value acquisition
The.xxxValue method gives you non-optional values.
// Return''if it is not a String or nil let name: String = json["name"].stringValue
8. Set Value
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. Raw Data
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. Other methods
exists
// Judging whether there is 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)
Output:
[ "first_name": "Theo", "last_name": "Tsao", "age": 22, "skills": ["Coding", "Reading", "Writing"], "address": [ "street": "Software St", "zip": "210012", "city": "Nanjing" ] ]