【问题标题】:Decode JSON file starting with "[" in SWIFT [duplicate]在 SWIFT 中解码以“[”开头的 JSON 文件 [重复]
【发布时间】:2020-04-22 11:45:23
【问题描述】:

我有这个结构。我知道这个结构不正确。

import Foundation

struct Country: Codable {
    var name: String
    var capital: String
}

我有 JSON 文件 https://restcountries.eu/rest/v2/name/eesti?fields=name;capital JSON文件以“[”开头,所以我只是不明白如何编码。 这是我第一次尝试对这个 JSON 文件进行编码。

override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://restcountries.eu/rest/v2/name/eesti?fields=name;capital"
        let url = URL(string: urlString)
        guard url != nil else {
            return
        }
        let session = URLSession.shared
        let dataTask = session.dataTask(with: url!) {(data, response, error) in
            if error == nil && data != nil {
                let decoder = JSONDecoder()

                do {

                    let countries = try decoder.decode(Country.self, from: data!)
                    print(countries[0].capital)
                    print(countries[0].name)
                } catch {
                    print("Error in json parsing")
                }
            }
        }.resume()
    }

【问题讨论】:

    标签: ios json swift encoding


    【解决方案1】:

    您正在接收一个 json 数组,因此您需要将其解码为数组而不是对象

      let countries = try decoder.decode(Array<Country>.self, from: data!)
    

    【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多