【问题标题】:Fetching data from multi level JSON从多级 JSON 中获取数据
【发布时间】:2020-10-06 06:32:12
【问题描述】:

我在从 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()

【问题讨论】:

    标签: json swift xcode


    【解决方案1】:

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

    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)
                    }
                }   
            }  
        }
    }
    

    更好的方法是使用 JSONDecoder 将 JSON 解析为结构体

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多