Swift JSON 解析类 Unbox
Posted swift语言
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift JSON 解析类 Unbox相关的知识,希望对你有一定的参考价值。
简单易用的Swift JSON 解析类 Unbox。
示例代码:
01 |
//JSON数据 |
02 |
{ |
03 |
"name" : "John" , |
04 |
"age" : 27 |
05 |
} |
06 |
07 |
//结构体User |
08 |
struct User { |
09 |
let name: String |
10 |
let age: Int |
11 |
} |
12 |
13 |
//User扩展Unboxable |
14 |
extension User: Unboxable { |
15 |
init (unboxer: Unboxer) throws { |
16 |
self .name = try unboxer.unbox(key: "name" ) |
17 |
self .age = try unboxer.unbox(key: "age" ) |
18 |
} |
19 |
} |
20 |
21 |
22 |
//解析 |
23 |
let user: User = try unbox(dictionary: dictionary) |
24 |
//或 |
25 |
let user: User = try unbox(data: data) |
指定KeyPath:
01 |
//JSON格式 |
02 |
{ |
03 |
"name" : "John" , |
04 |
"age" : 27 , |
05 |
"activities" : { |
06 |
"running" : { |
07 |
"distance" : 300 |
08 |
} |
09 |
}, |
10 |
"devices" : [ |
11 |
"Macbook Pro" , |
12 |
"iPhone" , |
13 |
"iPad" |
14 |
] |
15 |
} |
16 |
17 |
struct User { |
18 |
let name: String |
19 |
let age: Int |
20 |
let runningDistance: Int |
21 |
let primaryDeviceName: String |
22 |
} |
23 |
24 |
extension User: Unboxable { |
25 |
init (unboxer: Unboxer) throws { |
26 |
self .name = try unboxer.unbox(key: "name" ) |
27 |
self .age = try unboxer.unbox(key: "age" ) |
28 |
//下面两行指定keyPath |
29 |
self .runningDistance = try unboxer.unbox(keyPath: "activities.running.distance" ) |
30 |
self .primaryDeviceName = try unboxer.unbox(keyPath: "devices.0" ) |
31 |
} |
32 |
} |
开源代码主页 ❤
文章来自:51swift
以上是关于Swift JSON 解析类 Unbox的主要内容,如果未能解决你的问题,请参考以下文章
使用 swift 将 JSON 检索到的 int32 解析为核心数据类