Search code examples
jsonswiftserializationwifivpn

Error json serialization keyNotFound(CodingKeys... - when I am using Wi-Fi or VPN Connection


I have a function that is to get data from Server but sometimes when the application does request through a Wifi or a VPN I obtain . Why it happens when the application does request through wifi or VPN?

Error:

Error json serialization keyNotFound(CodingKeys(stringValue: "host", intValue: nil),
 Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "recommendations", intValue:
 nil), _JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "blockedHosts",
 intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "No value 
associated with key CodingKeys(stringValue: \"host\", intValue: nil) (\"host\").", 
underlyingError: nil))

Model:

class ListOfPlayers: Decodable {
    let players: [Player]
    let recommendations: [Recommendations]
    let proxies: [Proxies]
    let preloadAdStartPageUrl: String
}

class Recommendations: Decodable {
    let id: Int
    let url: String
    let title: String
    let color: String
    let image: String?
    let blockedHosts: [BlockedHostsRecommendation]
}

class BlockedHostsRecommendation: Decodable {
    let host: String
    let countries: [String]
}

I repeat, the application works well, but sometimes I catch this error only through Wifi or VPN.


Solution

  • I'd suggest capturing network traffic with a proxy like Charles and analyze the received data. The error message shows that JSONDecoder can't decode BlockedHostsRecommendation.host, it can be possible that in some cases you backend doesn't provide that field