我是JSON的新手。我已经完成了一些阅读,但我仍然感到困惑,而且我遇到了错误。
如何解析以下数据?
[{"symbol":"ALI","date":"1/22/2018","open":44.9000,"high":45.5000,"low":44.9000,"close":45.2000,"bid":45.1500,"ask":45.2000,"volume":6698800,"value":303245610.0000,"netForeign":-42279365.0000}]
我想单独获取每个字符串。
例如:符号,日期等
非常感谢任何帮助。谢谢!
作为参考,我尝试了以下解决方案,但出现了错误: How to parse Json object in swift 3
答案 0 :(得分:5)
在Swift 4中,使用Decodable
协议非常简单:
let jsonString = """
[{"symbol":"ALI","date":"1/22/2018","open":44.9000,"high":45.5000,"low":44.9000,"close":45.2000,"bid":45.1500,"ask":45.2000,"volume":6698800,"value":303245610.0000,"netForeign":-42279365.0000}]
"""
struct Item : Decodable {
let symbol, date : String
let open, high, low, close, bid, ask, value, netForeign : Double
let volume : Int
}
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode([Item].self, from: data)
print(result)
} catch {
print("error: ", error)
}
甚至将日期字符串解码为Date
struct Item : Decodable {
let symbol : String
let date : Date
let open, high, low, close, bid, ask, value, netForeign : Double
let volume : Int
}
do {
let data = Data(jsonString.utf8)
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let result = try decoder.decode([Item].self, from: data)
print(result)
} catch {
print("error: ", error)
}
这是将JSONDecoder
和URLSession
放在一起的示例:
let url = URL(string: "https://api.whatever...")!
URLSession.shared.dataTask(with:url) { (data, _, error) in
if error != nil {
print(error!)
} else {
do {
let result = try JSONDecoder().decode([Item].self, from: data!)
print(result)
} catch {
print("error: ", error)
}
}
}.resume()
请了解阅读 JSON。这很简单。只有两种集合类型(数组,字典)和四种值类型(字符串,数字,布尔值和空值)。另请参阅this question中的答案: