可编码和自定义字段解码

时间:2019-01-09 14:17:05

标签: json swift codable

我正在使用Codable协议和JSONDecoder解码从Web服务获取的JSON。而且效果非常好。但是,有一件事是,我有时会获得不同格式的Date,所以我想为此字段设置自定义解码。

通过SO和网络浏览,我发现可以做到这一点,但是我还必须手动解码所有其他字段。由于我有很多字段,因此我想自动解码所有字段,然后只对这一个字段进行手动解码。

这可能吗?

编辑:

我将提供更多信息,因为这个问题似乎引起了很多困惑。

我有包含许多字段的JSON。我的结构人采用Codable。我这样使用JSONDecoder

let person = try self.jsonDecoder.decode(Person.self, from: data)

现在所有字段都自动设置为struct。但是有时我会在一个或多个字段中手动对其进行解码。在这种情况下,它只是日期,可以采用多种格式。我想尽可能使用以下同一行:

let person = try self.jsonDecoder.decode(Person.self, from: data)

,其中所有其他字段将自动解码,而只有Date才具有手动编码。

1 个答案:

答案 0 :(得分:0)

您只需将用于解码的dateDecodingStrategy中的JSONDecoder设置为formatted并提供具有指定格式的DateFormatter,然后如果失败,则提供其他日期格式。查看带有示例的完整工作代码:

struct VaryingDate: Decodable {
    let a:String
    let date:Date
}

let jsonWithFirstDate = "{\"a\":\"first\",\"date\":\"2019/01/09\"}".data(using: .utf8)!
let jsonWithSecondDate = "{\"a\":\"first\",\"date\":\"2019-01-09T12:12:12\"}".data(using: .utf8)!

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithFirstDate) // succeeds
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithSecondDate) // fails, as expected
} catch {
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithSecondDate) // succeeds with the updated date format
}
相关问题