Search code examples
iosjsonswiftdecodablejsondecoder

Why do I get ‘Cannot get keyed decoding container -- found null value instead.’ error when I use JSONDecoder


(unknown context at $10741e078).CodingKeys>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil)

my model is ,

struct Details : Decodable {

    var userInfo : RequestUserInfo
    var commercialInfo : String?

}

struct RequestUserInfo : Decodable {

    var UserName : String?
    var Email : String?
    var UserIdentity : String?
    var UserMobile : String?
    var ThirdName : String?
    var LastName : String?
    var IdIssueDate : String?
    var IdSourceCity : String?


}

(unknown context at $10741e078).CodingKeys>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil)


Solution

  • You need to mark the types as Optional (?) wherever you're expecting null in the JSON.

    But, the issue with the above parsing is different from the one you described in the question.

    typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "newRequest", intValue: nil), CodingKeys(stringValue: "parcels", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "UsingPurposeId", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

    This can be resolved like so,

    The type of UsingPurposeId in BuildingRequestParcelDetails must be Int? instead of String?

    Parse the data in following way,

    do {
        let response = try JSONDecoder().decode(BuildingRequestDetails.self, from: data)
        print(response)
    } catch {
        print(error)
    }