【发布时间】:2019-03-31 22:11:34
【问题描述】:
我在 Swift 4.2 中遇到了 JSON 解析问题。这是显示运行时错误的以下代码。
我的 Json 数据如下,我从服务器获取的。
{
code: 406,
message: "Email Address already Exist.",
status: 0
}
我正在使用 Codable 来创建我的结构,如下所示
struct Registration: Codable {
var code: Int
var status: Int
private enum CodinggKeys: String, CodingKey {
case code
case status
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
self.code = Int(try container.decode(String.self, forKey: .code))!
} catch DecodingError.typeMismatch {
let value = try container.decode(Double.self, forKey: .code)
self.code = Int(value);
}
do {
self.status = try container.decode(Int.self, forKey: .status)
} catch DecodingError.typeMismatch {
let value = try container.decode(String.self, forKey: .status)
self.status = Int(value);
}
}
}
但每次我在解析 status 键时遇到错误。
注意:我曾尝试在 String、Int、Double、Decimal、NSInterger 中解析状态,但都没有。每次我得到同样的错误。 应解码 UInt,但找到了一个数字。
【问题讨论】:
-
其他字段有效吗?此外,
CodingKey枚举的名称中有错字。CodinggKeys而不是CodingKeys。这可能是问题吗?也许它正在从您的项目中获取另一个枚举,而不是您刚刚声明的枚举 -
你如何测试你的模型?它在 PlayGround 上对我有用。
-
pastebin.com/0UynM1wa 工作正常..
-
请显示原始服务器响应,而不是一些调试器输出。
-
添加您收到的 JSON 响应,以便我们调试问题。如果您在问题中添加的 JSON 是正确的,则此处无需
init(from:)。Codable可以自动处理。
标签: ios json codable decodable swift4.2