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/

相关文章:

javascript - 当 JSONP 数据改变时

json - 如何将 Drupal 服务默认响应格式更改为 JSON?

Swift If 程序

c++ - 检查 map 中的两个相同值

python - 修改数据框单元格中的字典

list - Prolog - 寻找替代词(同义词)

json - 具有 Spring Data Elasticsearch 的查询生成器

Java:在 Restful 服务中创建包含多个值的 JSON 响应

iphone - ARKit 是否公开了一种显示地平面的自动方式,还是应该将其作为对象添加到某些坐标

ios - 当应用程序在前台时如何显示 firebase 通知