用到第三方库 SwiftyJSON
func testDemo() {
let jsonStr = "[{\"name\": \"hangge\", \"age\": 100, \"phones\": [{\"name\": \"公司\",\"number\": \"123456\"}, {\"name\": \"家庭\",\"number\": \"001\"}]}, {\"name\": \"big boss\",\"age\": 1,\"phones\": [{ \"name\": \"公司\",\"number\": \"111111\"}]}]"
if let jsonData = jsonStr.data(using: .utf8, allowLossyConversion: false) {
///使用JSONSerialization
let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [[String: Any]]
if array != nil, array!.count > 0 {
if let in1:[String:Any] = array![0] {
if let phones = in1["phones"] as? [[String: Any]] {
let phone = phones.first
if let nub = phone?["number"] as? String {
DebugLog(nub)
}
}
}
}
///使用SwiftyJSON https://blog.csdn.net/ly410726/article/details/80235007
do {
let json = try JSON(data: jsonData)
if let name = json[0]["phones"][10]["name"].string {
DebugLog(name)
}
if let dic = json[0]["phones"][0].dictionary {
DebugLog(dic)
DebugLog(dic["number"])
}
} catch {
DebugLog("SwiftyJSON catch:\(error.localizedDescription)")
}
}
}
网友评论