Swift Model 与 JSON 转换

首先声明,这里不考虑 JSONSerializationJSONSerialization.jsonObject(with: jsonData, options: [])JSONSerialization.data(withJSONObject: data, options: []),使用 JSONDecodeJSONEncode

原因:

  1. JSONEncode JSONDecode
  2. What’s the difference between using JSONSerialization and JSONDecoder in swift?
  3. JSONDecoder vs. JSONSerialization… FIGHT!
  4. It’s Time to Abandon SwiftyJSON / 是时候放弃 SwiftyJSON
  5. JSON 與 Swift Codable 的介紹
  6. Swift http json

Model 转 JSON

定义 Model 的结构,需要声明结构遵循 Codable 协议。Codable 协议是一个组合协议,同时声明了 Decoable 和 Encodable 协议。

1
2
3
4
5
struct User: Codable {
let id: Int
let name: String
let age: Int
}

之后:

1
2
3
4
5
6
7
8
9
10
11
12
13
let user = User(id: 1, name: "haha", age: 25)

let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .prettyPrinted]

do {
let jsonData = try encoder.encode(user) // 到这一步就转换成功了
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
} catch {
print(error.localizedDescription)
}

其中:

.prettyPrinted 的作用是将打印时的

1
{"id":1,"name":"haha","age":25}

优化为:

1
2
3
4
5
{
"id":1,
"name":"haha",
"age":25
}

.sortedKeys 的作用是对字典进行排序:

  1. Swift的字典排序问题
  2. Dictionary Key Order in Swift 4 JSONEncoder
  3. iOS开发字典转json之后顺序会变

JSON String 转 JSON

1
2
3
4
5
let jsonString = "{\"name\":\"wall\",\"age\":\"22\",\"hobby\":\"ball\"}"
guard let jsonData = jsonString.data(using: .utf8) else {
print("Failed to jsonString -> jsonData")
return
}

JSON 转 Model

1
2
3
4
5
6
7
8
let decoder = JSONDecoder()

do {
let user = try decoder.decode(User.self, from: jsonData)
print(user.name)
} catch {
print(error.localizedDescription)
}

定义复杂的 Model 结构

数组一

JSON 格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"users": [
{
"id": 1,
"name": "haha",
"age": 25
},
{
"id": 2,
"name": "xixi",
"age": 25
}
]
}

对应的 Model 结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct UserList: Codable {

let users: [User]

struct User: Codable {
let id: Int
let name: String
let age: Int
}
}

let decoder = JSONDecoder()

do {
let userList = try decoder.decode(UserList.self, from: jsonData)
print(userList.users)
} catch {
print(error.localizedDescription)
}

参考:Swift原生:JSON转换Model

数组二

JSON 格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
[
{
"id": 1,
"name": "haha",
"age": 25
},
{
"id": 2,
"name": "xixi",
"age": 25
}
]

对应的 Model 结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct User: Codable {
let id: Int
let name: String
let age: Int
}

let decoder = JSONDecoder()

do {
let users = try decoder.decode([User].self, from: jsonData)
print(user)
} catch {
print(error.localizedDescription)
}

嵌套

JSON 格式如下:

1
2
3
4
5
6
7
8
9
{
"id": 1,
"name": "haha",
"age": 25,
"location": {
"country": "China",
"city": "Suzhou"
}
}

对应的 Model 结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct User: Codable {
let id: Int
let name: String
let age: Int
let location: Location
}

extension User {
struct Location: Codable {
let country: String
let city: String
}
}

参考:Swift中的JSON数据解析


Swift Model 与 JSON 转换
https://wonderhoi.com/2024/11/28/Swift-Model-与-JSON-转换/
作者
wonderhoi
发布于
2024年11月28日
许可协议