繁体   English   中英

从 SWIFT 中的 url 进行 JSON 解码

[英]JSON decode from url in SWIFT

我正在尝试从 URL 解码以下 JSON:

{
"date":"2018-08-17",
"data":[
       {"id":"IDD","rate":"1.1","name":"My test ID"},
       {"id":"IDX","rate":"101.12","name":"Another test ID"}
       ]
}

我的 swift 文件看起来像:

struct Container: Codable {
let date: String
let data: [MyData]
}

struct MyData: Codable {
let id: String
let rate: Double
let name: String
}

// This outputs the required json string    
if let url = URL(string: "https://www.xxx.php") {

do {
    let contents = try Data(contentsOf: url)

    do {
        let decoder = JSONDecoder()
        let jData: Container = try decoder.decode(Container.self, from: contents)

        print("The data presented is from \(jData.date)")

        for id in jData.data {
            // Here I want to get an array of the json data
            print(id.id)
        }

    } catch {
        print(error.localizedDescription)
    }

} catch {
    print(error.localizedDescription)
}

}

我的代码抛出错误:无法读取数据,因为它的格式不正确。

我究竟做错了什么? 您是否也有关于如何改进我的代码的建议?

谢谢你的帮助!

问题是这一行:

let rate: Double

将其更改为:

let rate: String

我相信问题在于 rate 在您的 data class 中是 Double ,但在您的 JSON rate 中是一个字符串。 将数据类中的速率更改为:

let rate: String

或者更改您的 JSON 以在比率中使用数字而不是字符串:

{
"date":"2018-08-17",
"data":[
       {"id":"IDD","rate":1.1,"name":"My test ID"},
       {"id":"IDX","rate":101.12,"name":"Another test ID"}
       ]
}

编辑:对不起,我刚刚注意到已经有一个基本上说同样的话的答案。 :)

您应该使用 URLSessionTask 异步下载数据。 否则应用程序将无响应和滞后。

其次,您应该将 rate 更改为 String 或在自定义 init 方法中提供自定义解码器以将其转换为 double

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM