简体   繁体   中英

Parsing JSON with Decodable in Swift Error

I want to parse a short JSON request from an HTTP Request with a struct and the decodable function. The declaration looks like:

struct Wert: Codable {
    let age: String
    let first_name: String
}

let session = URLSession.shared
    let url = URL(string: "https://learnappmaking.com/ex/users.json")!

And my Code to make the request and try to parse:


            guard let data = data else { return }

            do {
                let preis = try JSONDecoder().decode(Wert.self, from: data)
                print(preis);
            }
                catch {
                    print("JSON error: \(error.localizedDescription)")
                }
        }.resume()

I do get the error: "JSON error: The data couldn't be read because it isn't in the correct format." And I don't know what is wrong with the code

The JSON looks like:

  {
    "first_name": "Ford",
    "last_name": "Prefect",
    "age": 5000
  },
  {
    "first_name": "Zaphod",
    "last_name": "Beeblebrox",
    "age": 999
  },
  {
    "first_name": "Arthur",
    "last_name": "Dent",
    "age": 42
  },
  {
    "first_name": "Trillian",
    "last_name": "Astra",
    "age": 1234
  }
]

Would be nice if someone can help me.

Error:

The JSON the you're using is invalid. The valid JSON will be,

[{"first_name":"Ford","last_name":"Prefect","age":5000},{"first_name":"Zaphod","last_name":"Beeblebrox","age":999},{"first_name":"Arthur","last_name":"Dent","age":42},{"first_name":"Trillian","last_name":"Astra","age":1234}]

Model:

Use Int as data type for age instead of String ,

struct Wert: Decodable {
    let firstName, lastName: String
    let age: Int
}

Parsing:

1. Use [Wert].self instead of Wert.self while parsing, ie

2. Use decoder.keyDecodingStrategy = .convertFromSnakeCase to handle the snake-case (underscore) keys in the JSON , ie

if let url = URL(string: "https://learnappmaking.com/ex/users.json") {
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let data = data {
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let preis = try decoder.decode([Wert].self, from: data)
                print(preis)
            } catch {
                print(error)
            }
        }
    }.resume()
}

You would require to provide the coding keys for custom keys.

struct Wert: Codable {
    let age: String
    let firstName: String

    enum CodingKeys: String, CodingKey {
        case age, firstName = "first_name"
    }
}

Age is not a string type in your Json file, update your mapping as bellow.

struct Wert: Codable {
    let age: Int
    let first_name: String
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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