如何在swift中调整JSON解码器的类型



我定义了这样一个模型:

struct DMTest: Codable {
var uid: Int
var name: String?
}

并像这样进行模型解码:

let jsonStr = "{"uid":123,"name":"haha"}"
let jsonData = jsonStr.data(using: .utf8)!
do {
let decoder = JSONDecoder()
let result = try decoder.decode(DMTest.self, from:jsonData)
XCGLogger.debug("result = (result)")
}catch {
XCGLogger.debug("error")
}

当jsonStr如下所示时,它运行良好:

{"uid":123,"name":"haha"}

当jsonStr如下所示时,它将抛出一个异常:

{"uid":"123","name":"haha"}

这意味着,如果"uid"的类型不是适配器,则无法对其进行解码。但有时服务器的框架是弱类型的,它可能会给我这样的脏数据,我该如何调整类型?

例如:我在模型中定义了Int,如果服务器给出一些String类型的数据,我可以将其转换为Int,只需解码为Int即可,否则会抛出ecxeption。

您可以定义一个自定义解析解决方案:

struct DMTest: Codable {
enum CodingKeys: String, CodingKey {
case uid, name
}
var uid: Int
var name: String?
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let stringUID = try? container.decode(String.self, forKey: .uid), let intUID = Int(stringUID) {
uid = intUID
} else if let intUID = try? container.decode(Int.self, forKey: .uid) {
uid = intUID
} else {
uid = 0 // or throw error
}
name = try container.decodeIfPresent(String.self, forKey: .name)
}
}

最新更新