我有一个字典的字典,我需要将其转换为 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/