我正在尝试解码一个包含关联值的枚举。我尝试了以下代码,但它一直抛出异常。
let jsonString = """
{
"route": "petDetails"
}
"""
let jsonData = jsonString.data(using: .utf8)
struct Post: Decodable {
let route: Route
}
enum Route: Decodable, Equatable {
case petDetails(String)
init?(rawValue: String) {
switch rawValue {
case "petDetails":
self = .petDetails("")
default:
return nil
}
}
private enum CodingKeys: String, CodingKey {
case petDetails
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(String.self, forKey: .petDetails) {
self = .petDetails(value)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Data doesn't match"))
}
}
}
try! JSONDecoder().decode(Post.self, from: jsonData!)
I get the following error:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "route", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
有什么想法我可能遗漏了吗?
route
键可以是 Int 或 String 类型? - RobJSON
文件,这将有助于我们更好地理解。 - RobJSON
应该长这样:route: {"pet_details" : "abc" }
,而不是route: "petDetails"
。它期望解码一个包含该枚举值的字典,但你提供的是一个字符串,所以才会抛出错误。 - Roblet route: String
。 - vadian