预计会解码Int,但会找到一个数字

Jat*_*han 5 json ios codable decodable swift4.2

我在Swift 4.2中遇到了JSON解析的问题.以下是显示运行时错误的以下代码.

我的Json数据如下所示,我从服务器获得.

{
    code: 406,
    message: "Email Address already Exist.",
    status: 0
}
Run Code Online (Sandbox Code Playgroud)

我使用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);
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

但每次我解析状态键时都会出错.

注意:我曾尝试在String,Int,Double,Decimal,NSInterger中解析状态但是没有任何工作.每次我都得到同样的错误.预计解码UInt但会找到一个数字.

Ger*_*eon 17

错误消息非常误导.当JSON包含布尔值,并且struct具有相应键的Int属性时,会发生这种情况.

很可能你的JSON 实际上是这样的:

{
    "code": 406,
    "message": "Email Address already Exist.",
    "status": false
}
Run Code Online (Sandbox Code Playgroud)

因此,你的结构应该是

struct Registration: Codable {
    let code: Int
    let status: Bool
}

if let registration = try? JSONDecoder().decode(Registration.self, from: data) {
    print(registration.code) // 406
    print(registration.status) // false
}
Run Code Online (Sandbox Code Playgroud)