[英]How can I decode partially double serialized json string using `Codable` protocol?
[英]How can I call `didSet` method using `Codable` protocol
如何使用可Codable
协议调用didSet
方法。
class Sample: Codable{
var text : String? {
didSet {
print("didSet") // do not call
extended_text = "***" + text! + "***"
}
}
var extended_text : String?
}
let sample_json = "{\"text\":\"sample text\"}"
let decoder = JSONDecoder()
let sample = try! decoder.decode(Sample.self, from: sample_json.data(using: .utf8)!)
print(sample.text!)
print(sample.extended_text ?? "")
而不是使用didSet,您应该仅使extendedText
为只读的计算属性。 请注意,命名属性时,使用camelCase
而不是snake_case
是Swift惯例:
struct Sample: Codable {
let text: String
var extendedText: String {
return "***" + text + "***"
}
}
let sampleJson = """
{"text":"sample text"}
"""
do {
let sample = try JSONDecoder().decode(Sample.self, from: Data(sampleJson.utf8))
print(sample.text) // "sample text\n"
print(sample.extendedText) // "***sample text***\n"
} catch {
print(error)
}
如果您的目标是在初始化Codable结构时运行方法,则可以选择编写自己的自定义解码器:
class Sample: Codable {
let text: String
required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
text = try container.decode(String.self)
print("did set")
}
}
let sampleJson = "{\"text\":\"sample text\"}"
let decoder = JSONDecoder()
do {
let sample = try decoder.decode([String: Sample].self, from: Data(sampleJson.utf8))
print(sample["text"]?.text ?? "")
} catch {
print(error)
}
这将打印:
确实
示范文本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.