我有一些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正在工作。我真的不知道爲什麼解碼中存在這樣的不一致性。
Xcode Playground Gist is available here
'CodingKeys',不'codingKeys'。 – Hamish
Doh!驚人的是一雙額外的眼睛可以做什麼。謝謝! –
是否每個字段都是可選的?你可以發送'{}',你會期望解碼所有的nils(你會認爲這些nils不同於空字符串或false)? 「profile_image_url」被髮送爲「」「'這一事實使得這一點非常可疑。使用這種許多可選項通常是數據問題的標誌。 –