SwiftUI-JSON序列化、反序列化
Swift5 自带解析
extension Encodable{
func toJson() -> String {
return String(data: try! JSONEncoder().encode(self), encoding: .utf8) ?? ""
}
}
extension String{
func toModel<T:Decodable>() -> T? {
do{
return try JSONDecoder().decode(T.self, from: self.data(using: .utf8)!)
}catch{
}
return nil
}
}
结构体实现 Codable 协议:里面的字段为基础类型或者结构体(结构体实现 Codable),不能有 protocol 类型
具体示例
/// 界面元素
struct MUIContent:Codable{
var key : String
var desc : String?
var content : String // 元素内容
init<T : MUI>(mui:T) {
self.key = T.key
self.desc = mui.desc
self.content = mui.toJson()
}
}
protocol MUI:Codable{
static var key : String {
get}
var desc : String? {
get}
}
/// 小组件数据
struct MWidget: Codable{
var list: [MUIContent] = [] //元素列表
var backgroud: MWidgetBackgroud?
mutating func append<T:MUI>(t:T) {
let content = MUIContent(mui: t)
list.append(content)
}
}
/// 小组件背景
struct MWidgetBackgroud:Codable {
var color:Int = 0xFFFFFFFF
var image:String?
var borderWidth:Float = 0
var borderColor:Int = 0xFFFFFFFF
}
struct MDateUI : MUI {
static var key: String = "date"
var desc: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale.current
return dateFormatter.string(from: Date())
}
var offsetX: Float = 0
var offsetY: Float = 0
var fontSize: Float = 14
}
let KEY_DATE = "date"
let KEY_TIME = "time"
struct MTimeUI : MUI {
static var key: String = "time"
var desc: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.locale = Locale.current
return dateFormatter.string(from: Date())
}
var offsetX: Float = 0
var offsetY: Float = 0
var fontSize: Float = 14
}
let MUIKeyMapp:[String:Any] = [
KEY_TIME : MTimeUI.self,
KEY_DATE : MDateUI.self
]
extension Encodable{
func toJson() -> String {
return String(data: try! JSONEncoder().encode(self), encoding: .utf8) ?? ""
}
}
extension String{
func toModel<T:Decodable>() -> T? {
do{
return try JSONDecoder().decode(T.self, from: self.data(using: .utf8)!)
}catch{
}
return nil
}
}
var m = MWidget()
m.append(t: MDateUI())
m.append(t: MTimeUI())
print(m.toJson())
let mJson = #"""
{
"list":[{
"key":"date","desc":"2021-08-04","content":"{\"offsetX\":10,\"offsetY\":10,\"fontSize\":14}"},{
"key":"time","desc":"11:03","content":"{\"offsetX\":11,\"offsetY\":11,\"fontSize\":24}"}]}
"""#
欢迎和我一起交流学习
- 个人网站: https://hanks.pub
- Github: https://github.com/hanks-zyh
- zhihu: https://www.zhihu.com/people/yuhan-zhang-36
- 微信公众号:Hanks软件库
文章来自: http://hanks-zyh.github.io/
还没有评论,来说两句吧...