I want to decode JSON using JSONDecoder
. It is working as expected, but for the JSON where inner object is empty JSONDecoder
throws an error The data couldn’t be read because it is missing.
Sample JSON on Error:
{
"header": {
"code": 1053,
"message": "Incorrect information."
},
"body": {}
}
Sample JSON on Success:
{
"header": {
"code": 1053
"message": "Nice information."
},
"body": {
"client_id": 12345
}
}
Success JSON, it is decoded easily. But on Error JSON, It's throwing error.
Here is the code I'm using
struct ApiResponse: Decodable {
let header: Header
let body: Body
struct Header: Decodable {
let responseCode: Int
let message: String
}
struct Body: Decodable {
let clientId: Int
}
}
let decoder: JSONDecoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodedResponse = try decoder.decode(ApiResponse.self, from: data)