Swift解析Json

使用

Json文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"startCursor": "0",
"endCursor": "0",
"list": [
{
"id": 195524,
"name": "测试1",
"paid": true
},
{
"id": 195508,
"name": "测试2",
"paid": true
}
]
}

结构体

结构体
1
2
3
4
5
struct LessonListItem: Codable {
let id: Int64
let name: String
let paid: Bool
}

解析Json文件

解析Json文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//要获取文件中“list”下的数据,需要手动创建一个结构体
struct CardList: Codable {
let list: [LessonListItem] //在decode时会把“list”对应的数据返回到该属性上
}

func loadJson(filename fileName: String) -> [LessonListItem]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let jsonData = try JSONDecoder().decode(CardList.self, from: data)
return jsonData.list
} catch {
print("error:\(error)")
}
}
return nil
}

为属性选择可选的keys

为属性选择可选的keys
1
2
3
4
5
6
7
8
9
struct Landmark: Codable {
var name: String
var foundingYear: Int

enum CodingKeys: String, CodingKey {
case name = "title" //json中的“title”数据也能映射到name上
case foundingYear = "founding_date"
}
}

映射不同level的数据

映射不同level的数据
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
//json中的数据:
"latitude":
"additionalInfo":
"elevation":
//结构体中的数据:
"latitude":
"additionalInfo":
"elevation":

struct Coordinate {
var latitude: Double
var elevation: Double

//第一级的key
enum CodingKeys: String, CodingKey {
case latitude
case additionalInfo
}

//第二级的key
enum v: String, CodingKey {
case elevation
}
}
//实现decode
extension Coordinate: Decodable {
init(from decoder: Decoder) throws {
//获取第一级的映射集
let values = try decoder.container(keyedBy: CodingKeys.self)
latitude = try values.decode(Double.self, forKey: .latitude)
//获取第二级的映射集
let additionalInfo = try values.nestedContainer(
keyedBy: AdditionalInfoKeys.self,
forKey: .additionalInfo
)
elevation = try additionalInfo.decode(Double.self, forKey: .elevation)
}
}
//实现encode
extension Coordinate: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(latitude, forKey: .latitude)

var additionalInfo = container.nestedContainer(
keyedBy: AdditionalInfoKeys.self,
forKey: .additionalInfo
)
try additionalInfo.encode(elevation, forKey: .elevation)
}
}
0%