首页 > 解决方案 > JSON decode from url in SWIFT

问题描述

I am trying to decode the following JSON from an URL:

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

My swift file looks like:

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)
}

}

My code throws the error: The data couldn’t be read because it isn’t in the correct format.

What am I doing wrong? Do you maybe also have a suggestion on how to improve my code in general?

Thanks for your help!

标签: jsonswifturl

解决方案


我认为问题在于 rate 在您的数据类中是 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"}
       ]
}

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


推荐阅读