我有一个JSON查询的以下响应。如何将字典表示为可编码的?我缩短了JSON响应以节省空间。
{
"result":[
{
"delivery_address": "",
"made_sla": "true",
"watch_list": "",
"upon_reject": "cancel",
"location": {
"link": "https://foo.com/api/now/table/cmn_location/753ac76f4fd9320066bfb63ca310c79b",
"value": "753ac76f4fd9320066bfb63ca310c79b"
}
}
]
}
struct ResultList : Codable {
let result: [Result]
}
struct Result : Codable {
let delivery_address: String
let made_sla: String
let watch_list: String
let upon_reject: String
let location: Location
}
struct Location: Codable {
let link: String?
let value: String?
}
let decoder = JSONDecoder()
do {
let todo = try decoder.decode(ResultList.self, from: responseData)
print("todo \(todo)")
} catch {
print("error trying to convert data to JSON")
print(error)
}
我得到以下错误:
"Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
最佳答案
基于所有的评论,我相信您实际解码的JSON看起来更像这样:
{
"result": [{
"delivery_address": "",
"made_sla": "true",
"watch_list": "",
"upon_reject": "cancel",
"location": {
"link": "https://foo.com/api/now/table/cmn_location/753ac76f4fd9320066bfb63ca310c79b",
"value": "753ac76f4fd9320066bfb63ca310c79b"
}
},
{
"delivery_address": "",
"made_sla": "true",
"watch_list": "",
"upon_reject": "cancel",
"location": ""
}
]
}
所以有些记录有一个位置,有些记录将位置编码为空字符串。基本上,在很多级别上,这确实是一个混乱的JSON,无论生成什么代码,都应该被修复。坏消息我肯定不会发生。好消息是我们至少可以在本地修复。
我们将不得不手工解码,所以我们不妨在这里清理所有的残局。首先,这些名称与Swift命名约定不匹配。我们可以使用
CodingKeys
修复这个问题。我们还可以为当前类型错误的字符串提供实数类型(Bool和拒绝枚举)。enum Rejection: String, Codable {
case cancel
}
struct Result : Codable {
let deliveryAddress: String
let madeSLA: Bool
let watchList: String
let uponReject: Rejection
let location: Location?
private enum CodingKeys: String, CodingKey {
case deliveryAddress = "delivery_address"
case madeSLA = "made_sla"
case watchList = "watch_list"
case uponReject = "upon_reject"
case location
}
}
现在我们只需要能够解码它。请注意,我将位置设置为可选。显然,它有时不存在,所以您要么需要缺省值,要么需要是可选的。我选择了后者。解码所有这些是非常直接的:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
deliveryAddress = try container.decode(String.self, forKey: .deliveryAddress)
madeSLA = try container.decode(String.self, forKey: .madeSLA) == "true"
watchList = try container.decode(String.self, forKey: .watchList)
uponReject = try container.decode(Rejection.self, forKey: .uponReject)
location = try? container.decode(Location.self, forKey: .location)
}
最后一行是你的实际问题。它只是说,如果我们不能将其解码为
Location
,请将其设置为nil。在这里我们可以更严格一些,首先尝试将其解码为一个位置,然后将其解码为一个字符串,然后检查字符串是否为空,但是对于任何解码失败,在这里使用nil都是合理的。关于ios - 如何在“可编码”响应中使用字典?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47145823/