-3

I have read about every stackoverflow question on this I can find, but sadly none of the solutions worked for me.

The goal is to convert a JSON file with the following example structure:

[{"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"}]

to the following struct:

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

This is where data is downloaded and attempted to be decoded:

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

Sadly I am getting the following error:

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

I would be very grateful if anyone can point me in the right direction!

Thank you!

Enea Dume
  • 3,014
  • 3
  • 21
  • 36
Sam
  • 51
  • 1
  • 7
  • Try to take id as String not Int – shivi_shub Jul 23 '18 at 10:52
  • Please learn to read JSON. It's very simple. **Everything** in double quotes is `String` even `"1"` or `"false"`. There are no exceptions. Floating point numeric values are `Double`, all others `Int`. `true / false` (no double quotes) is `Bool`. `[]` is array, `{}` is dictionary. That's it. That's the entire JSON type set. – vadian Jul 23 '18 at 10:57
  • in this snippet `"id":"1"` you clearly see the value is a `String` not an `Int`, you need to deal with it considering this. – holex Jul 23 '18 at 11:03
  • I'm sorry, I missed the exclamation marks and have now corrected the JSON to feature correct value types. Thank you! – Sam Jul 23 '18 at 12:10

1 Answers1

0

Id is String not Int , and all of them inside ""

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

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

    }
}

//

You can make use of the catch block to see the error you have in decoding like this

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)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87