Nested Swift 4 Codable Struct 不规则使用 CodingKeys

Nested Swift 4 Codable Struct uses CodingKeys irregularly

我有一些 JSON 正在尝试使用符合 Codable 协议的 Swift 结构进行解码。主结构似乎不想识别 thread_type 的 codingKey 别名,而是愉快地使用显式命名的 thread_id 属性。有问题的结构如下:

struct Message: Codable {
var id: String?
var type: String?
var thread_id: String?
var threadType: String?
var sender: User?
var body: String?
var media: String?
var sentAt: Double?
var unread: Bool?
var status: String?
var url: String?

enum codingKeys: String, CodingKey {
    case id
    case type
    case thread_id
    case threadType = "thread_type"
    case sender
    case body
    case media
    case sentAt = "sent_at"
    case unread
    case status
    case url
}
}

我正在尝试解析的 JSON:

let json =
"""
{
"id": "Jvbl6LY",
"type": "sms",
"thread_id": "60LrVL7",
"thread_type": "578a",
"delay_until": null,
"sender": {
"id": "EVkdNBx",
"type": "user",
"first_name": "Jerry",
"last_name": "Ward",
"mobile_number": "123-456-7890",
"profile_image_url": "",
"is_online": false,
"email": "jerryw+demo@jypsee.com"
},
"body": "Here is a picture of our Coquille Suite.  Let me know if you would like a reservation?",
"media": "",
"sent_at": 1509133604000.167,
"unread": false,
"status": "",
"url": "https://connect-staging.jypsee.com/api/sms/threads/60LrVL7/history/Jvbl6LY/"
}
"""

最后解码器调用自身:

let decoder = JSONDecoder()
let data = json.data(using: .utf8)!
do {
    let message = try decoder.decode(Message.self, from: data)
    print(message.thread_id)
    print(message.threadType)
    print(message.sender?.firstName)
    print(message.sender?.lastName)
} catch {
    print(error)
}

message.thread_id 打印出 Optional("60LrVL7")\n",这是预期的。 message.threadType 打印出 nil\n,这不是预期的。更奇怪的是 message.sender?.firstName 和 message.sender?.lastName 分别打印 "Optional("Jerry")\n""Optional("Ward")\n"。这意味着嵌套的 User Codable Struct CodingKey 正在工作。我真的很困惑为什么在解码时会出现这种不一致。

Xcode Playground Gist is available here

Apple 文档在以下段落的第一句中明确说明。 需要一个名为 'CodingKeys' 的特殊枚举。 (我遇到了类似的问题,花了很长时间才找出来)。

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types