Fork me on GitHub

Swift Codable

基本使用

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
// 基本使用
func a1() {

// 我们有模型如下
// 要使用 Codable 需要模型遵守 Codable 协议
struct User: Codable {
var userId: Int?
var name: String?
var height: CGFloat?
}
let jsonString =
"""
{
"userId": 1,
"name": "Jack",
"height": 1.7,
}
"""
let decoder = JSONDecoder()
if let data = jsonString.data(using: String.Encoding.utf8) {
if let user = try? decoder.decode(User.self, from: data) {
print(user)
}
}
}

jsonString -> data

1
2
// jsonString -> data
_ = "{}".data(using: String.Encoding.utf8)

Dictionary -> data

1
2
3
4
5
6
7
8
9
10
// dict -> data
let jsonDic = [
"userId": 1,
"name": "Jack",
"height": 1.7,
] as [String : Any]
guard JSONSerialization.isValidJSONObject(jsonDic) else {
return
}
_ = try? JSONSerialization.data(withJSONObject: jsonDic, options:[])

data -> Dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let jsonDic = [
"userId": 1,
"name": "Jack",
"height": 1.7,
] as [String : Any]

// dict -> data
if let data = try? JSONSerialization.data(withJSONObject: jsonDic, options:[]) {

// data -> dict
// json 解析
if let dic = try? JSONSerialization.jsonObject(with: data, options: []) {
print(dic)
}
}

Key替换

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
func a2() {

struct User: Codable {
var userId: Int?
var desc: String?

// 模型的 Key : 服务器返回 Key
enum CodingKeys: String, CodingKey {
case userId
case desc = "description"
}
}

let jsonString =
"""
{
"userId": 1,
"description": "Jack",
}
"""

let decoder = JSONDecoder()
if let data = jsonString.data(using: String.Encoding.utf8) {
if let user = try? decoder.decode(User.self, from: data) {
print(user)
}
}
}
- END -
扫一扫上面的二维码图案,加我微信

文章作者:梁大红

特别声明:若无特殊声明均为原创,转载请注明,侵权请联系

版权声明:署名-非商业性使用-禁止演绎 4.0 国际