json - 嵌套字典转换为 json swift

标签 json swift dictionary

我有一个字典的字典,我需要将其转换为 Json。

[
    Dict1:1, 
    test: A Value, 
    NestedDict1:[
        city: A City Name, 
        address: An Address, 
        NestedDict2: [
            1: 1, 
            39: 2
        ],
        favorite1: 2, 
        favorite3: Chocolate
    ]
]

当我使用

NSJSONSerialization.dataWithJSONObject(myJsonDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

它只编码最外层的字典。所以我的输出看起来像这样:

{
    "Dict1":"1", 
    "test": "A Value", 
    "NestedDict1":"[
        city: A City Name, 
        address: An Address, 
        NestedDict2: [
            1: 1, 
            39: 2
        ],
        favorite1: 2, 
        favorite3: Chocolate
    ]"
}

我如何对内部字典进行 JSON 处理?

最佳答案

swift 3

let myJsonDict : [String: Any] = [
    "Dict1": "1",
    "test": "A Value",
    "NestedDict1":[
        "city": "A City Name",
        "address": "An Address",
        "NestedDict2": [
            "1": "1",
            "39": "2"
        ],
        "favorite1": "2",
        "favorite3": "Chocolate"
    ]
]
let jsonObject = try? JSONSerialization.data(withJSONObject: myJsonDict, options: [])

if let jsonString = String(data: jsonObject!, encoding: .utf8) {
    print(jsonString)
}

输出

{"test":"A Value","Dict1":"1","NestedDict1":{"favorite1":2,"city":"A City Name","NestedDict2":{"1":"1","39":"2"},"favorite3":"Chocolate","address":"An Address"}}

关于json - 嵌套字典转换为 json swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744998/

相关文章:

java - 如何在java中迭代和比较Hashtable<String, Map<String, Set<String>>>

python - 创建 MS COCO 样式数据集

javascript - 循环遍历 JSON 响应对象

ios - 导航 Controller swift 中的中心搜索栏

c++ - 将多个值存储为 map 中的键的最佳方法是什么

C++有效地创建具有单个条目不同的 map

javascript - d3.JS JSON 数据导入 - 不在全局范围内

java - 如何使用 Moshi 将不同的对象属性反序列化为一个公共(public)类?

swift - Swift 中的简单容器绑定(bind)?

ios - 手动布局中的自动布局