嵌套的Swift 4 Codable Struct不规则地使用CodingKeys
问题描述:
我有一些JSON,我试图使用符合Codable协议的Swift结构进行解码。主结构似乎不想识别thread_type的codingKey别名,但很高兴地使用明确命名的thread_id
属性。有问题的结构低于:嵌套的Swift 4 Codable Struct不规则地使用CodingKeys
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": "[email protected]"
},
"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 IS正在工作。我真的不知道为什么解码中存在这样的不一致性。
答
苹果文档在下面的段落的第一句话明确规定。 需要一个名为'CodingKeys'的特殊枚举。 (我有类似的问题,并花了我相当长的时间才发现)。
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
'CodingKeys',不'codingKeys'。 – Hamish
Doh!惊人的是一双额外的眼睛可以做什么。谢谢! –
是否每个字段都是可选的?你可以发送'{}',你会期望解码所有的nils(你会认为这些nils不同于空字符串或false)? “profile_image_url”被发送为“”“'这一事实使得这一点非常可疑。使用这种许多可选项通常是数据问题的标志。 –