
9

如何将 JSON 字典编码为 JSONEncoder
source link: https://mp.weixin.qq.com/s/PI7s8cXxzErqOB0e9BHqvg
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如何将 JSON 字典编码为 JSONEncoder
Original
Swift君
Swift社区
2022-03-01 01:00
收录于话题
#Swift
47
个
#iOS
55
个
#Tips
72
个
??回复 “进群” 拉你进社区交流群??
Swift社区
做最好的 Swift 社区,我们的使命是做一个最专业最权威的 Swift 中文社区,我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货,不忘初心,牢记使命。
109篇原创内容
Official Account
JSONEncoder
处理类型安全,因此我们需要为所有可能的类型声明枚举 JSONValue
。我们还需要一个自定义 initializer
来从 JSON 字典中初始化 JSONValue
。
import Foundation
enum JSONValue {
case string(String)
case int(Int)
case double(Double)
case bool(Bool)
case object([String: JSONValue])
case array([JSONValue])
}
extension JSONValue: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let string): try container.encode(string)
case .int(let int): try container.encode(int)
case .double(let double): try container.encode(double)
case .bool(let bool): try container.encode(bool)
case .object(let object): try container.encode(object)
case .array(let array): try container.encode(array)
}
}
}
extension JSONValue {
init?(any: Any) {
if let value = any as? String {
self = .string(value)
} else if let value = any as? Int {
self = .int(value)
} else if let value = any as? Double {
self = .double(value)
} else if let value = any as? Bool {
self = .bool(value)
} else if let json = any as? [String: Any] {
var dict: [String: JSONValue] = [:]
for (key, value) in json {
dict[key] = JSONValue(any: value)
}
self = .object(dict)
} else if let jsonArray = any as? [Any] {
let array = jsonArray.compactMap { JSONValue(any: $0) }
self = .array(array)
} else {
return nil
}
}
}
var dict: [String: Any] = [
"anArray": [1, 2, 3],
"anObject": [
"key1": "value1",
"key2": "value2"
],
"aString": "hello world",
"aDouble": 1.2,
"aBool": true,
"anInt": 12
]
let encoder = JSONEncoder()
let value = JSONValue(any: dict)
let data = try! encoder.encode(value)
print(String(data: data, encoding: .utf8))
- EOF -
点赞和在看就是最大的支持❤️
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK