@propertyWrapper
public struct PropertyWrapperString: Codable {
public var wrappedValue: String?
public init(wrappedValue: String?) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
var value: String?
if let temp = try? container.decode(String.self) {
value = temp
} else if let temp = try? container.decode(Int.self) {
value = String(temp)
} else if let temp = try? container.decode(Float.self) {
value = String(temp)
} else if let temp = try? container.decode(Double.self) {
value = String(temp)
} else {
value = nil
}
wrappedValue = value
}
}
/// 必须重写,否则如果model缺省字段的时候会导致解码失败,找不到key
extension KeyedDecodingContainer {
func decode( _ type: PropertyWrapperString.Type, forKey key: Key) throws -> PropertyWrapperString {
try decodeIfPresent(type, forKey: key) ?? PropertyWrapperString(wrappedValue: nil)
}
}
/// encode 相应字段
extension KeyedEncodingContainer {
mutating func encode(_ value: PropertyWrapperString, forKey key: Key) throws {
try encodeIfPresent(value.wrappedValue, forKey: key)
}
}
Codable 任意基础数据类型处理为String
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 该项目源码地址:https://github.com/ggb2312/JavaNotes/tree/master/...
- Redis所有的key(键)都是字符串。我们在谈基础数据结构时,讨论的是存储值的数据类型,主要包括常见的5种数据类...
- 「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战[https://juejin.cn...
- 「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战[https://juejin.cn...
- java lang包不需要导包 1、字符串字面值可以被看成字符串对象 2、字符串是常量,一旦被赋值,就不能改变 t...