嵌套字典转换为json swift

时间:2015-06-10 00:12:02

标签: 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内部词典?

2 个答案:

答案 0 :(得分:3)

我认为问题更多的是您对数据的表示。

如果您可以将所有键更改为Strings,那么它可以是字典,因为字符串符合Hashable。否则,它将被定义为Any,并且不能真正成为词典键。

这样做可以实现以下目的:

let myJsonDict : [String:AnyObject] = [
    "value": 1123,
    "test": "some string",
    "NestedDict1": [
        "city": "A City Name",
        "address": "An Address",
        "NestedDict2": [
            "1": 1,
            "39": 2
        ],
        "favorite1": 2,
        "favorite3": "Chocolate"
    ]
]

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


println(NSString(data: jsonObject!, encoding: NSUTF8StringEncoding)!)

给出以下输出:

{
  "test" : "some string",
  "NestedDict1" : {
    "city" : "A City Name",
    "address" : "An Address",
    "favorite3" : "Chocolate",
    "NestedDict2" : {
      "1" : 1,
      "39" : 2
    },
    "favorite1" : 2
  },
  "value" : 1123
}

答案 1 :(得分:3)

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"城市":" A   市   名称"" NestedDict2" {" 1":" 1"" 39":" 2" }," favorite3":"巧克力""地址":"安   地址"}}