Swift:将JSON解码为Int/Double

Swift: Decode JSON into Int/Double

我已经阅读了我能找到的关于此的每个 Whosebug 问题,但遗憾的是 none 的解决方案对我有用。

目标是转换具有以下示例结构的 JSON 文件:

[{"id":"1","poltopf_id":"22441208220850191","bearbeitungszeit":"13.35","station":"1"},{"id":"2","poltopf_id":"22441208220813267","bearbeitungszeit":"-2270785619.97","station":"1"}, {"id":"3","poltopf_id":"2244120822087035","bearbeitungszeit":"-2270785551.27","station":"1"}]

到以下结构:

struct ProcessingTimeRow: Decodable {

let elementNo: Int
let poltopf_id: Double
let processingTime: Double
let station: Int

enum CodingKeys : String, CodingKey {
    case elementNo = "id"
    case poltopf_id
    case processingTime = "bearbeitungszeit"
    case station
}

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    elementNo = try values.decode(Int.self, forKey: .elementNo)
    poltopf_id = try values.decode(Double.self, forKey: .poltopf_id)
    processingTime = try values.decode(Double.self, forKey: .processingTime)
    station = try values.decode(Int.self, forKey: .station)
}
}

这是下载数据并尝试解码的地方:

     URLSession.shared.dataTask(with: urlToDownload) {

                (data, response, error) in guard let data = data else {
                print("Something 

went wrong with data")
            return
            }

            do {
                self.dataReceived = true
                let decoder = JSONDecoder()
                let urlData = try decoder.decode([ProcessingTimeRow].self, from: data)
                print("UrlData: \(dump(urlData))")
            } catch let err {
                // Failed at downloading data
                self.dataReceived = false
                print("Error", dump(err))
            }

        }.resume()

很遗憾,我收到以下错误:

Swift.DecodingError.typeMismatch
  ▿ typeMismatch: (2 elements)
    - .0: Swift.Int #0
    ▿ .1: Swift.DecodingError.Context
      ▿ codingPath: 2 elements
        ▿ _JSONKey(stringValue: "Index 0", intValue: 0)
          - stringValue: "Index 0"
          ▿ intValue: Optional(0)
            - some: 0
        - CodingKeys(stringValue: "id", intValue: nil)
      - debugDescription: "Expected to decode Int but found a string/data instead."
      - underlyingError: nil

如果有人能指出正确的方向,我将不胜感激!

谢谢!

Id 是 String 而不是 Int ,而且都在 ""

struct ProcessingTimeRow: Codable {
    let elementNo, poltopfID, processingTime,station: String

    enum CodingKeys: String, CodingKey {
        case elementNo = "id",poltopfID = "poltopf_id", processingTime = "bearbeitungszeit" ,station

    }
}

//

你可以像这样使用catch块来查看你在解码时遇到的错误

let str = """
    [{"id":"1","poltopf_id":"22441208220850191","bearbeitungszeit":"13.35","station":"1"},{"id":"2","poltopf_id":"22441208220813267","bearbeitungszeit":"-2270785619.97","station":"1"}, {"id":"3","poltopf_id":"2244120822087035","bearbeitungszeit":"-2270785551.27","station":"1"}] 
"""

do {

    let rr =  try JSONDecoder().decode([ProcessingTimeRow].self, from: str.data(using: .utf8)!)

    print(rr)
}
catch {

    print(error)
}