RajPannu1241
RajPannu1241

Reputation: 1

How do I correctly format my structures to the API I am using?

I am using the Aplhadvantage API. Its structure is:

{
    "Global Quote": {
        "01. symbol": "MSFT",
        "02. open": "152.4100",
        "03. high": "163.7100",
        "04. low": "152.0000",
        "05. price": "162.0100",
        "06. volume": "96388312",
        "07. latest trading day": "2020-02-28",
        "08. previous close": "158.1800",
        "09. change": "3.8300",
        "10. change percent": "2.4213%"
    }
}

I have already created my structures:

import Foundation

struct StockResponse: Decodable{
    var response: Stocks
}

struct Stocks: Decodable{
    var stocks: [StockInfo]
}

struct StockInfo: Decodable{
    var open: String
    var high: String
    var low: String
    var close: String
    var volume: String
}

And my decoder is :

    func getStock (completion: @escaping(Result<[StockInfo], StockError>) -> Void) {
        let dataTask = URLSession.shared.dataTask(with: resourceURL) { data, _,_ in
            guard let jsonData = data else{
                completion(.failure(.noDataAvailable))
                return
            }
            do{
                let decoder = JSONDecoder()
                let stocksResponse = try decoder.decode(StockResponse.self, from: jsonData)
                let stockDetails = stocksResponse.response.stocks
                completion(.success(stockDetails))
            }
            catch{
                completion(.failure(.canNotProcessData))
            }
        }
        dataTask.resume()
    }

Each time I run the code, I get the canNotProcessData error. So the program successfully gets the data, but it cant process it. How would I go about fixing that?

Upvotes: 0

Views: 49

Answers (1)

Mac3n
Mac3n

Reputation: 4719

You can use QuickType to convert your data to the standard swift model. your structure keys are different from your response.

it should be something like this:

// MARK: - DataClass
struct DataClass: Codable {
    let globalQuote: GlobalQuote

    enum CodingKeys: String, CodingKey {
        case globalQuote = "Global Quote"
    }
}

// MARK: - GlobalQuote
struct GlobalQuote: Codable {
    let the01Symbol, the02Open, the03High, the04Low: String
    let the05Price, the06Volume, the07LatestTradingDay, the08PreviousClose: String
    let the09Change, the10ChangePercent: String

    enum CodingKeys: String, CodingKey {
        case the01Symbol = "01. symbol"
        case the02Open = "02. open"
        case the03High = "03. high"
        case the04Low = "04. low"
        case the05Price = "05. price"
        case the06Volume = "06. volume"
        case the07LatestTradingDay = "07. latest trading day"
        case the08PreviousClose = "08. previous close"
        case the09Change = "09. change"
        case the10ChangePercent = "10. change percent"
    }
}

Upvotes: 1

Related Questions