我使用新的 Codable 协议(protocol)将结构转换为 JSON,然后转换为字典以用于测试目的。问题是结构中的字典变量没有被转换回来并保持 Any
而不是 [Int: String]
struct Person: Codable {
var name: String?
var history: [Int: String]
init() {
self.name = "Name"
history = [0: "Test"]
}
}
let person = Person()
let jsonData = try JSONEncoder().encode(person)
let result = try JSONSerialization.jsonObject(with: jsonData, options: [])
let dictionary = result as? [String: Any]
print(dictionary)
这给了我以下结果
Optional(["history": {
0 = Test;
}, "name": Name])
当我期待
Optional(["history":[0: "Test"]], "name": "Test"])
对于为什么会发生这种情况的任何解释,或者更好的是,如何基本上进行深度 JSON 序列化的解决方案,我将不胜感激。
我正在添加一个演示问题的 Playground : https://www.dropbox.com/s/igpntk7az0hevze/JSONSerialisation.playground.zip
最佳答案
当您使用JSONEncoder
进行编码时,您还可以使用JSONDecoder
对json 数据进行解码。在这种情况下,history
是一个字典,它不是默认类型之一,因此添加带有自定义的 init(from decoder: Decoder)
将是一种解决方法预期的字典。
struct Person: Codable {
var name: String
var history: [Int: String]
init() {
self.name = "Name"
history = [0: "Test"]
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Failed to decode name"
self.history = try container.decodeIfPresent([Int: String].self, forKey: .history) ?? [-1: "Failed to decode history"]
}
}
let person = Person()
do {
let jsonData = try JSONEncoder().encode(person)
if let result = try? JSONDecoder().decode(Person.self, from: jsonData) {
print(result)
}
} catch {
print(error.localizedDescription)
}
关于json - 使用 swift 将 JSON 嵌套到嵌套字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193930/