【问题标题】:Json Parsing Swift using an Api (alpha vantage)使用 Api 解析 Swift 的 Json (alpha vantage)
【发布时间】: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 DataTime Series (Daily) 的字典) 2) 您必须添加 CodingKeys 以映射包含空格并以开头的键有效结构成员名称的数字。请看stackoverflow.com/questions/56485249/…
  • 错误 #3:请注意,根据 JSON 规范,双引号中的 everythingString,甚至是 "481.3400""false"

标签: arrays json swift api parsing


【解决方案1】:

你需要像这样修改你的结构并解码如下:-

结构:

struct Stock: Codable {
    let metaData: MetaData
    let timeSeriesDaily: [String: TimeSeriesDaily]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeriesDaily = "Time Series (Daily)"
    }
}

struct MetaData: Codable {
    let the1Information, the2Symbol, the3LastRefreshed, the4OutputSize: String
    let the5TimeZone: String

    enum CodingKeys: String, CodingKey {
        case the1Information = "1. Information"
        case the2Symbol = "2. Symbol"
        case the3LastRefreshed = "3. Last Refreshed"
        case the4OutputSize = "4. Output Size"
        case the5TimeZone = "5. Time Zone"
    }
}

struct TimeSeriesDaily: Codable {
    let the1Open, the2High, the3Low, the4Close: String
    let the5Volume: String

    enum CodingKeys: String, CodingKey {
        case the1Open = "1. open"
        case the2High = "2. high"
        case the3Low = "3. low"
        case the4Close = "4. close"
        case the5Volume = "5. volume"
    }
}

URLSession:

URLSession.shared.dataTask(with: URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=TSLA")!) { (data, _, _) in
    let stock = try! JSONDecoder().decode(Stock.self, from: data!)
    print(stock)
}.resume()

注意:这只是一个例子,你应该自己处理错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2019-02-16
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多