从多级JSON获取数据

Vix大块头

我在从json文件中获取产品“名称”时遇到问题。

这是json输出

到目前为止,这是我的代码。并输出完整的json。我只想从此文件中获取产品名称。

guard let url = URL(string: "https://URL/get_products.php") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let dataResponse = data,
              error == nil else {
              print(error?.localizedDescription ?? "Response Error")
              return }
        do{
            let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: [])
            print(jsonResponse)
         } catch let parsingError {
            print("Error", parsingError)
       }
    }
    task.resume()
瓦迪安

结构非常清晰,字符串键旁边的值是字典,序号旁边的值是数组:

if let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse) as? [String:Any],
   let data = jsonResponse["data"] as? [[String:Any]] {
    for anItem in data {
        if let products = anItem["products"] as? [[String:Any]] {
            for product in products {
                if let name = product["name"] as? String {
                    print(name)
                }
            }   
        }  
    }
}

更好的方法是将JSON解析为 JSONDecoder

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章