SwiftyJSON的使用
- 1.拷贝SwiftyJSON.swift到项目。
- 2.使用
let jsonStr = "[{\"name\": \"name swift\", \"age\": 100, \"phones\": [{\"name\": \"公司\",\"number\": \"123456\"}, {\"name\": \"家庭\",\"number\": \"001\"}]}, {\"name\": \"big boss\",\"age\": 1,\"phones\": [{ \"name\": \"公司\",\"number\": \"111111\"}]}]"
print(jsonStr)
let jsonData = jsonStr.data(using: .utf8)
let arrData = JSON(data:jsonData!)
print(arrData)
print(arrData[0])
print(arrData[0]["name"])
let name2:String = arrData[1]["name"].string!
print(name2)
// 数字变量的用法
let iRandom:Int = Int(1)!
let path: [JSONSubscriptType] = [iRandom,"name"]
let name = arrData[path].string
- 3.高级使用JSON的 .description
// 删除一个成员
let jdata = jsonStr.data(using: .utf8)
var arrData = JSON(data:jdata!)
// print(arrData.description)
arrData[indexPath.row] = ""
var newStrMember = "["
for i in 0..<arrData.count {
let strOneJson:String = arrData[i].description
if strOneJson != "" {
if i == arrData.count - 1 {
newStrMember = newStrMember + arrData[i].description
} else {
newStrMember = newStrMember + arrData[i].description + ","
}
}
}
newStrMember += "]"
-4 path
//Getting a string using a path to the element
let path: [JSONSubscriptType] = [1,"list",2,"name"]
let name = json[path].string
//Just the same
let name = json[1]["list"][2]["name"].string
//Alternatively
let name = json[1,"list",2,"name"].string
//With a custom way
let keys:[SubscriptType] = [1,"list",2,"name"]
let name = json[keys].string