Дми*_*аев 3 xcode json nsdictionary ios swift
我的 api 中有结构
{
"Hall":"Hall",
"Date":20180501,
"Prices":[
{
"Time":1,
"Price":4000
},
{
"Time":2,
"Price":4000
},
{
"Time":3,
"Price":4000
}
]
}
Run Code Online (Sandbox Code Playgroud)
现在我卡住了,无法取出价格和时间。我知道有很多问题,但我还是不明白,请帮助。
我使用这个代码:
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()
}
Run Code Online (Sandbox Code Playgroud)
我是 json 的新手,刚开始学习它。我知道这很容易,但我无法弄清楚。我也知道我可以使用 codable 和 decodeable,但现在我需要在这个实现中获得价格和时间。
首先不要使用NSArray / NSDictionary,使用原生 Swift 类型。
key 的值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"]!)
}
}
Run Code Online (Sandbox Code Playgroud)
但是我建议将 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"}
}
Run Code Online (Sandbox Code Playgroud)
do {
let result = try JSONDecoder().decode(Item.self, from: data!)
print(result)
} catch { print(error) }
Run Code Online (Sandbox Code Playgroud)