json - Swift 4 JSON 解析(预期解码 Array<Any> 但发现字典)

标签 json swift parsing swift4

我似乎无法获得解码此 API 的正确结构。这都是字典 ({...}),但我的代码一直试图将其解构为数组。

错误代码:

 Error serialising json typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
2018-04-25 22:41:50.570999+0100 APItest[40741:729417] TIC Read Status [1:0x0]: 1:57
2018-04-25 22:41:50.571127+0100 APItest[40741:729417] TIC Read Status [1:0x0]: 1:57

解析API链接: https://api.coinbase.com/v2/exchange-rates?currency=BTC

代码:

func mainExchanges(){
    let jsonUrlString = "https://api.coinbase.com/v2/exchange-rates?currency=BTC"
    guard let url = URL(string: jsonUrlString) else
    { return }

    URLSession.shared.dataTask(with: url)
        { (data,response,err) in
            guard let data = data else
            {
                print("Error: No data to decode")
                return
            }
            do
            {
                let exchanges = try
                    JSONDecoder().decode([Exchanges].self, from: data)
                print(exchanges[0].data.rates.EUR)
            }
            catch let jsonErr
                {
                    print("Error serialising json",jsonErr)
                }
        }
    .resume()
}

结构:

 struct Exchanges: Decodable   {
        let data: currency

        struct currency: Decodable {
            let currency: String
            let rates: Rates

            struct Rates: Decodable {
                let GBP: String
                let EUR: String
                let USD: String
            }
        }
    }

我也试过将其构造为

struct Exchanges {} 
     struct currency {}
         struct rates {}

最佳答案

您的数据不是数组,而是字典。 要解析它,您可以使用:

let exchanges = try
                JSONDecoder().decode(Exchanges.self, from: data)

如果你想将它转换为数组,那么将新的数组对象创建为:

let exchange: [Exchanges] = [exchanges]

关于json - Swift 4 JSON 解析(预期解码 Array<Any> 但发现字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031856/

相关文章:

json - 如何在Laravel 5中获取原始json请求有效载荷?

javascript - 在文本框中插入 id 后,单击使用 ajax php sql 在 html 表中输入填充数据

javascript - 如何调用 he.js 函数来解码 JSON 输出元素

ios - swift 错误 : "class cannot be constructed because it has no accessible initializers"

swift - 使用 Swift 和核心数据

python - 值错误 : unknown url type

javascript - 使用 PHP 中的 JSON 进行 JSON 解析

ios - 最大输入后禁用 UITextField 光标移动

json - 可以引用 JSON 数字吗?

c++ - Antlr4 语法意外错误(C++ 目标)