需要编码为 JSON,这是一个具有 2 个日期实例变量(日期和时间)的结构,但是,我需要使用不同的格式对每个日期实例变量进行编码,即。对于“天”:“yyyy-Md”和“时间”:“H:m:s”。
编写了一个没有问题的自定义解码器。但不确定如何编写所需的自定义编码器来解决这个问题。
例如,我可以解码以下 JSON 字符串: { "biometrics" : [ {"biometricId":1,"amount":2.1,"source":"Alderaan","day":"2019-1-3"," time":"11-3-3","unitId":2}, {"biometricId":10,"amount":3.1,"source":"Endoor","day":"2019-2-4" ,"时间":"11-4-4","unitId":20}] }
但是,当我对其进行编码时,我只能以单一日期格式对其进行编码:( 帮助,将不胜感激。谢谢。
import UIKit
let biometricsJson = """
{ "biometrics" : [
{"biometricId":1,"amount":2.1,"source":"Alderaan","day":"2019-1-3","time":"11-3-3","unitId":2},
{"biometricId":10,"amount":3.1,"source":"Endoor","day":"2019-2-4","time":"11-4-4","unitId":20}]
}
"""
struct Biometrics: Codable {
var biometrics: [Biometric]
}
struct Biometric: Codable {
var biometricId: Int
var unitId: Int
var source: String?
var amount: Double
var day: Date
var time: Date
init(biometricId: Int, unitId: Int, source: String, amount: Double, day: Date, time: Date){
self.biometricId = biometricId
self.unitId = unitId
self.source = source
self.amount = amount
self.day = day
self.time = time
}
}
extension Biometric {
static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "H:m:s"
if let date = formatter.date(from: dateString) {
return date
}
formatter.dateFormat = "yyyy-M-d"
if let date = formatter.date(from: dateString) {
return date
}
throw DecodingError.dataCorruptedError(in: container,
debugDescription: "Cannot decode date string \(dateString)")
}
return decoder
}()
}
let biometrics = try Biometric.decoder.decode(Biometrics.self, from:biometricsJson.data(using: .utf8)!)
let jsonEncoder = JSONEncoder()
let encodedJson = try jsonEncoder.encode(biometrics)
let jsonString = String(data: encodedJson, encoding: .utf8)
if biometricsJson != jsonString {
print("error: decoding, then encoding does not give the same string")
print("biometricsJson: \(biometricsJson)")
print("jsonString: \(jsonString!)")
}
我希望编码的 JSON 可以被解码器解码。即 biometricsJson == jsonString