嵌套字典转换为json swift [英] nested dictionaries converted to json swift

查看:275
本文介绍了嵌套字典转换为json swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要转换为Json的字典词典.

I Have a Dictionary of Dictionaries that I need to convert to 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)

它仅对最外面的字典进行编码.所以我的输出看起来像这样:

it only encodes the outer most dictionary. So my output looks something like this:

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

我还如何使用JSON内部字典?

How do I JSON the inner dictionaries as well?

推荐答案

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值","Dict1":"1","NestedDict1":{"favorite1":2,"city":"A 城市 名称","NestedDict2":{"1":"1","39":"2"},"favorite3":"Chocolate","address":"An 地址}}

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

这篇关于嵌套字典转换为json swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆