gpt4 book ai didi

ios - 从 NSDictionary 获取 JSON 数据

转载 作者:可可西里 更新时间:2023-11-01 01:09:02 26 4
gpt4 key购买 nike

我的 api 中有结构

{
"Hall":"Hall",
"Date":20180501,
"Prices":[
{
"Time":1,
"Price":4000
},
{
"Time":2,
"Price":4000
},
{
"Time":3,
"Price":4000
}
]
}

现在我卡住了,无法提取价格和时间。我知道有很多问题,但我还是不明白,请帮忙。

我使用这段代码:

let url = URL(string: "http://<...>/api/prices?hall=<...>&date=20180501")

var request = URLRequest(url: url!)

request.httpMethod = "GET"

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

if let err = error {
print(err)
} else {

do {

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {

// ...

}

DispatchQueue.main.async {
self.collectionView.reloadData()
}

} catch {
print("error")
}
}
})
task.resume()
}

我是 json 新手,刚开始学习它。我知道这很容易,但我想不通。我也知道我可以使用 codable 和 decodable,但现在我需要在此实现中获得价格和时间。

最佳答案

首先不要使用NSArray/NSDictionary,使用原生的Swift类型。

Prices 的值是一个 [String:Int] 字典数组:

if let jsonResult = try JSONSerialization.jsonObject(with: data!) as? [String:Any], 
let prices = jsonResult["Prices"] as? [[String:Int]] {
for price in prices {
print(price["Time"]!, price["Price"]!)
}
}

但是我建议将 JSON 解码为一个在 Swift 4 中非常简单的结构

struct Item : Decodable {
let hall : String
let date : Int
let prices : [Price]

private enum CodingKeys : String, CodingKey { case hall = "Hall", date = "Date", prices = "Prices"}
}

struct Price : Decodable {
let time, price : Int

private enum CodingKeys : String, CodingKey { case time = "Time", price = "Price"}
}

do {
let result = try JSONDecoder().decode(Item.self, from: data!)
print(result)
} catch { print(error) }

关于ios - 从 NSDictionary 获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com