【发布时间】:2020-09-21 08:14:02
【问题描述】:
Swift Json 解析
我正在尝试解析 json 以分配值。我是 swift 新手,无法在 YouTube 或网络上找到解决方案。我不确定我是否必须拥有与 json 的“”内部相同的构造,但有一个空格。此外,我不确定日期是否用于调用当天的信息。
struct Stock: Decodable {
let symbol: String
let open: Double
let high: Double
let low: Double
let close: Double
let volume: Int
}
var tag : String = "TSLA"
let url = URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=/(key)")
let session = URLSession.shared
session.dataTask(with: url!) { (data, response, error) in
// pull what is coming from the interent
if let response = response {
print(response)
}
// print the data but it wont be unpacked
if let data = data {
print(data)
}
// json serialization
do{
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
let stock = try
JSONDecoder().decode(Stock.self, from: data!)
print(Stock.init(symbol: String, open: Double, high: Double, low: Double, close: Double, volume: Int))
} catch {
print(error)
}
}.resume()
打印 json 示例:
"Meta Data" = {
"1. Information" = "Daily Prices (open, high, low, close) and Volumes";
"2. Symbol" = TSLA;
"3. Last Refreshed" = "2020-06-01";
"4. Output Size" = Compact;
"5. Time Zone" = "US/Eastern";
};
"Time Series (Daily)" = {
"2020-01-08" = {
"1. open" = "473.7000";
"2. high" = "498.4900";
"3. low" = "468.2300";
"4. close" = "492.1400";
"5. volume" = 31199393;
};
"2020-01-09" = {
"1. open" = "497.1000";
"2. high" = "498.8000";
"3. low" = "472.8700";
"4. close" = "481.3400";
"5. volume" = 28463186;
};
"2020-01-10" = {
"1. open" = "481.7900";
"2. high" = "484.9400";
"3. low" = "473.7000";
"4. close" = "478.1500";
"5. volume" = 12976832;
【问题讨论】:
-
两个致命错误:1) 您必须从顶部解码(带有键
Meta Data和Time Series (Daily)的字典) 2) 您必须添加 CodingKeys 以映射包含空格并以开头的键有效结构成员名称的数字。请看stackoverflow.com/questions/56485249/… -
错误 #3:请注意,根据 JSON 规范,双引号中的 everything 是
String,甚至是"481.3400"和"false"
标签: arrays json swift api parsing