SwiftUI-JSON序列化、反序列化

Swift5 自带解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123


/// 界面元素
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}"}]}
"""#

欢迎和我一起交流学习

文章来自: http://hanks-zyh.github.io/