简体   繁体   English

如何在swift4中解析对象内部数组中的json对象

[英]how to parse json object inside array inside object in swift4

How can I JSON object inside an array in swift4? 如何在swift4中的数组内建立JSON对象? How ca I get the response for this JSON in swift4? 如何在swift4中获取此JSON的响应? I am printing the location but its's getting nil . 我正在打印位置,但是位置nil

Here its my JSON data: 这是我的JSON数据:

{
    "Details": [{
        "phone": 
        "id":
    }],
    "address": [{
       "location": "some location"
   }]
}

 do {
     let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]

     let location = json["location"] as? [[String: AnyObject]]
     print(location)

 } catch {         
     print("error")       
 }

json["location"] doesn't exist and therefore is not an array. json["location"]不存在,因此不是数组。 Location is inside the address array. 位置在地址数组内。

try 尝试

if let addressArray = json["address"] as? [[String: Any]] {
    let address = addressArray.first
    let location = address?["location'] as? String
    print(location)
} 

NOTES 笔记

  1. In your JSON location was missing any value ie "location": I added a String 在您的JSON位置中缺少任何值,即"location":我添加了一个字符串
  2. it's better to use the Codable protocol in Swift 4 最好在Swift 4中使用Codable协议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM