【问题标题】:nested dictionaries converted to json swift嵌套字典转换为 json swift
【发布时间】:2015-08-25 00:51:38
【问题描述】:

我有一本字典需要转换为 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 格式?

【问题讨论】:

  • 试试不为options:参数传递.PrettyPrinted
  • 为什么有人投了反对票?对我来说看起来是一个非常有效的问题!!!
  • @nhgrif 尝试不先进行漂亮的打印,数据最终相同,只是外部被编码
  • @kbgn27 该链接实际上是一个字典数组,似乎对我的字典问题没有帮助

标签: json swift dictionary


【解决方案1】:

斯威夫特 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 城市 Name","NestedDict2":{"1":"1","39":"2"},"favorite3":"Chocolate","address":"An 地址"}}

【讨论】:

    【解决方案2】:

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

    如果您可以将所有键更改为字符串,那么它可以是一个字典,因为字符串符合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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 2021-05-21
      • 2023-02-23
      • 2019-06-18
      • 1970-01-01
      • 2022-12-05
      • 2020-09-03
      • 2013-12-07
      相关资源
      最近更新 更多