json - 使用 swift 将 JSON 嵌套到嵌套字典中

标签 json swift dictionary nsjsonserialization codable

我使用新的 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/

相关文章:

json - 如何在不为整个应用程序重新定义 `errorHandler` 的情况下从 JSON 处理程序发出 JSON 错误?

ios - 弱引用被清零,但对象尚未被释放

C# LINQ 通过比较键合并字典

php - file_put_contents 不适用于 json laravel 和 php

java - 从mongodb中提取特定字段

swift - 下载状态在重新加载时消失

python - 在Python中同时迭代2个不同的字典

python - 这种方法是否有更快的替代方法来从字典列表中获取最后更新消息?

java - 如何更紧凑地使用Gson的TypeToken?

ios - Return Observer.create 不返回并且旁边的代码不能使用 RxSwift 工作