Reputation:
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.
Upvotes: 0
Views: 1407
Reputation: 178
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
}
Upvotes: 0
Reputation: 24341
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, i.e.
2. Use decoder.keyDecodingStrategy = .convertFromSnakeCase
to handle the snake-case (underscore) keys in the JSON, i.e.
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()
}
Upvotes: 3
Reputation: 16341
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"
}
}
Upvotes: 0