ios - 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()
}
解决方案
你需要做。
转换
responsedata
为json
阅读你得到的甲酸盐(在这里你会得到字典)。
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()
推荐阅读
- reactjs - AWS Amplify - 如何在登录后呈现组件
- typescript - 在 Typescript 文件中导入 Firebase Analytics
- html - CSS Grid carousel - 最后一项正在缩小
- javascript - 是否有在我的 Android 上运行 JavaScript 项目的命令?
- python - solve_ivp 缺少 1 个必需的位置参数错误
- r - 如何在R中仅对匹配的键值求和
- xamarin.forms - android上的xamarin.forms Collectionview中没有可见的选择
- c++ - 是什么导致“指定给 RtlValidateHeap(01480000, 014A2900) C-SDL-Blackjack.exe 的地址无效已触发断点。” 在这个项目中?
- c# - 当数据从 C# 到达时,Angular 中的 getDay() 未定义
- java - 如何在可见的两个视图之间切换?