【发布时间】:2017-07-19 14:40:31
【问题描述】:
我使用新的 Codable 协议将结构转换为 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 序列化的解决方案。
我正在添加一个展示问题的游乐场: https://www.dropbox.com/s/igpntk7az0hevze/JSONSerialisation.playground.zip
【问题讨论】:
-
您为什么希望它看起来像这样?您正在打印的字典是完整的字典,数据似乎正是它应该是的。请记住,
[Int: String]不是一个数组,它是一个字典,{0 = Test;}是当您将字典打印到控制台进行调试时 Swift 格式化字典的方式......在我看来,您的代码工作正常。跨度> -
嗨,donnywals,实际上这不是 swift 打印字典的方式。如果我将字典定义为
let sampleDictionary: [String: Any] = ["history":[0: "Test"], "name": "Test"],然后将其打印为print(sampleDictionary),则结果为["history": [0: "Test"], "name": "Test"]。如果我尝试使用let history = dictionary["history"] as? [Int: String]访问历史记录,则该值为 nil,因为它不是字典。 -
哎呀......你似乎是绝对正确的丹尼斯!
标签: json swift dictionary nsjsonserialization codable