解码简单的API数组Swift

时间:2018-03-19 14:57:58

标签: swift api struct decode

我正在努力解码API返回的特定对象,我无法弄清楚正确的struct

怎么了?

以下是返回的API JSON

{
    "votes": [
     {
        "votesId": "1",
        "vote_nb": "6",
        "current_time": "0",
        "trend_up": "0",
        "trend_down": "0",
        "position_hold": "0",
        "position_buy": "0",
        "position_sell": "0"
    }]
}

我的代码decodefetch

struct VoteData : Codable {
    let votes : [Votes]
}

struct Votes : Codable {
    let vote_nb : String
}

func fetchData(completion: @escaping (VoteData?, Error?) -> Void) {

    let url = URL(string: "...")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else {
            completion(nil, error ?? APIError.unknownNetworkError)
            return
        }
        do {
            let result = try JSONDecoder().decode(VoteData.self, from: data); completion(result, nil)
            let vote_nb = result.votes.vote_nb // Value of type '[Votes]' has no member 'vote_nb'
            print("VOTE NUMBER: ", vote_nb)
        } catch let parseError {
            completion(nil, parseError)
        }
    }
    task.resume()
}

1 个答案:

答案 0 :(得分:0)

首先选择数组的特定成员,然后检查该成员的属性。

更改此行:

let vote_nb = result.votes.vote_nb

为此:

let vote_nb = result.votes[0].vote_nb