【问题标题】:How to remove square brackets from a dictionary output and replace with curly brackets?如何从字典输出中删除方括号并用大括号替换?
【发布时间】:2016-07-25 14:27:11
【问题描述】:

我是 Swift 的新手,如果这个问题听起来太傻,请原谅。 我正在尝试从字典数组输出中创建一个 JSON 对象,该输出必须在每个实体之后有花括号(“{}”)而不是方括号(“[]”)。我的代码如下。

import UIKit

var locations = Array<Dictionary<String, String>>()

var myLocations = ["pqr","xyz"]

myLocations.forEach {_ in 
    var dictionary = Dictionary<String, String>()
    dictionary["string1"] = "hello"
    dictionary["string2"] = "world"
    locations.append(dictionary)

}
print(locations)

对此的输出是:- [["string2": "world", "string1": "hello"], ["string2": "world", "string1": "hello"]] \n

但是我要求它为:- [{“string2”:“world”,“string1”:“hello”},{“string2”:“world”,“string1”:“hello”}] \n

我知道这样做的一种方法是使用过滤器数组,但我怀疑可能有一种更简单的方法,但在搜索了有关 Swift 的各种文档后我无法找到它。你能帮我解决这个问题吗?提前致谢。

【问题讨论】:

  • 你想要 JSON 吗?然后你可以使用NSJSONSerialization
  • 是的,你是对的。我试过这个,它似乎工作。谢谢!:)

标签: ios swift swift2


【解决方案1】:

输出是

[["string2": "world", "string1": "hello"], ["string2": "world", "string1": "hello"]]

因为这是一个 Swift 字典的 Swift 数组。

要将此对象转换为 JSON,不要自己解析和替换字符,而是使用 NSJSONSerialization:

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(locations, options: [])
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }
} catch {
    print(error)
}

打印:

[{"string2":"world","string1":"hello"},{"string2":"world","string1":"hello"}]

我们使用dataWithJSONObject 将您的Swift 对象转换为JSON数据,然后我们使用String(data:, encoding:) 将此JSON 数据转换为JSON 字符串

【讨论】:

  • 感谢您的快速回复!我刚试过这个,它奏效了。:)
  • 当我把它放入一个字符串时,它会在“”之前添加“/”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多