我有一些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 IS正在工作。我真的不知道为什么解码会出现这种不一致的原因。
答案 0 :(得分:3)
Apple doc在下面的段落的第一句中明确指出。 必须使用名为“CodingKeys”的特殊枚举。 (我遇到了类似的问题,花了很长时间才发现)。
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types