【发布时间】: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。 -
是的,你是对的。我试过这个,它似乎工作。谢谢!:)