首页 > 解决方案 > Swift 5 从 https 请求解析 Json 数据

问题描述

我正在尝试解析 json 并获取“价格”值。我如何解析 json 以在 swift 5 编程语言中实现这一点。我已经尝试过可编码的结构,但我一直得到一个空结果。

JSON

{
  "status" : "success",
  "data" : {
    "network" : "DOGE",
    "prices" : [
      {
        "price" : "0.37981",
        "price_base" : "USD",
        "exchange" : "binance",
        "time" : 1620014229
      }
    ]
  }
}

迅速

func api()

guard let url = URL(string: "https://sochain.com//api/v2/get_price/DOGE/USD") else { return }

        let task = URLSession.shared.dataTask(with: url) { data, response, error in

          guard let data = data, error == nil else { return }

           let dataString = String(data: data, encoding: .utf8)
  }
    
        task.resume()

}

标签: iosjsonswiftnsurlsession

解决方案


你需要做。

  1. 转换responsedatajson

  2. 阅读你得到的甲酸盐(在这里你会得到字典)。

        guard let url = URL(string: "https://sochain.com//api/v2/get_price/DOGE/USD") else { return }
    
         let task = URLSession.shared.dataTask(with: url) { data, response, error in
    
             guard let data = data, error == nil else { return }
    
             do {
                 // make sure this JSON is in the format we expect
                 // convert data to json
                 if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                     // try to read out a dictionary
                     print(json)
                     if let data = json["data"] as? [String:Any] {
                         print(data)
                         if let prices = data["prices"] as? [[String:Any]] {
                             print(prices)
                             let dict = prices[0]
                             print(dict)
                             if let price = dict["price"] as? String{
                                 print(price)
                             }
                         }
                     }
                 }
             } catch let error as NSError {
                 print("Failed to load: \(error.localizedDescription)")
             }
    
         }
    
         task.resume()
    

推荐阅读