当我使用 JSONDecoder 时,为什么会出现“无法获取键控解码容器——找到空值。”错误

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

($10741e078 处的未知上下文).CodingKeys>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil)

我的模型是,

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?


}

($10741e078 处的未知上下文).CodingKeys>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil)

你可以使用这个 ModelAPI - https://app.quicktype.io?share=NYC0PgFnypeo5cLho3sH 并使用代码 self.requestDetail = try JSONDecoder().decode(ModelAPI.self, from: json) 调用它。我已经检查过了,它有效。另外,我已经修复了你的 JSON(两行错误)

您需要将 Optional (?) 类型标记为 JSON 中的 null

但是,上述解析的问题与您在问题中描述的问题不同。

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))

可以这样解决,

BuildingRequestParcelDetailsUsingPurposeId的类型必须是Int?而不是String?

按以下方式解析数据,

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

在您的情况下,如果 Details.userInfo == 无

设置

var userInfo : RequestUserInfo?

你的错误就会消失。 但实际上你的错误隐藏在错误的数据中。在解码前尝试添加字符串:

print(String(data:  data, encoding: .ascii))

仔细检查是否一切正常。 例如,您可能会得到 "user_info" 而不是 key "userInfo"