Loading...

Parsing a JSON with a missing parameter


Im getting a JSON from a webpage, where i get the weather for an airport, and so far so good, it works, but one is

struct MetarResponse: Codable {

var windGust = Windgust

}

struct WindGust: Codable {
    var repr: String?
}

sometimes when it comes from the JSON i will give me

"wind_gust":{"repr":"37","value":37,"spoken":"three seven"},

But if this value is not present in the weather, it will give me

"wind_gust":null,

so right now i have the problem, that i only need to use repr value, and that does work with the Struct i have, but it crashes the app when i get the weather at a place that contains null instead.

How do i prevent it from crashing when i try to parse the JSON?

working code:

struct MetarResponse: Codable {

var windGust = Windgust?

}

struct WindGust: Codable {
    var repr: String?
}
- - Source

Answers

answered 1 week ago Joakim Danielson #1

You need to make your WindGust struct optional, something like

struct Weather: Codable {
    let windGust: WindGust?
}

Example

let data = """
    {"wind_gust":null}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

do {
    let weather = try decoder.decode(Weather.self, from: data)
    print(weather.windGust)
} catch {
    print(error)
}

answered 1 week ago Gabriel Henrique Paul #2

What you can do is check if you are getting what you want and provide a custom value so your system won't crash. Something like:

struct WindGust: Codable {
    var repr: String?

    enum CodingKeys: String, CodingKey {
        case repr
    }
}


extension WindGust: Decodable {

    init(from decoder: Decoder) throws {
        guard let repr = try decoder.container(keyedBy: CodingKeys.self) else {
             repr = "placeholder"
             return
        }
    }
}

This way you can manage when your json data aren't as you would expect, I haven't tried the code above, but hopefully you can get the idea. I also recommend this documentation by Apple.

comments powered by Disqus