如何从字典输出中删除方括号并用大括号替换?

时间:2016-07-25 14:27:12

标签: ios swift swift2

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

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)

输出到: - [[&#34; string2&#34;:&#34; world&#34;,&#34; string1&#34;:&#34; hello&#34; ],[&#34; string2&#34;:&#34; world&#34;,&#34; string1&#34;:&#34; hello&#34;]] \ n

但是我需要它: - [{&#34; string2&#34;:&#34; world&#34;,&#34; string1&#34;:&#34; hello&#34; },{&#34; string2&#34;:&#34; world&#34;,&#34; string1&#34;:&#34; hello&#34;}] \ n

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

1 个答案:

答案 0 :(得分:2)

输出

[["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)
}

打印:

  

[{ “字符串2”: “世界”, “字符串1”: “你好”},{ “字符串2”: “世界”, “字符串1”: “你好”}]

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

相关问题