如何将字典数组转换为JSON?

Tru*_*an1 3 json dictionary swift swift2

我有一系列字典,我想转换为JSON.我的对象是类型,[[String: AnyObject]]并希望最终得到这样的示例:

[
  { "abc": 123, "def": "ggg", "xyz": true },
  { "abc": 456, "def": "hhh", "xyz": false },
  { "abc": 789, "def": "jjj", "xyz": true }
]
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试的,但编译器不喜欢我的声明:

extension Array where Element == Dictionary<String, AnyObject> {
    var json: String {
        do { return try? NSJSONSerialization.dataWithJSONObject(self, options: []) ?? "[]" }
        catch { return "[]" }
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

A.G*_*A.G 9

斯威夫特 4

extension Collection where Iterator.Element == [String:AnyObject] {
    func toJSONString(options: JSONSerialization.WritingOptions = .prettyPrinted) -> String {
        if let arr = self as? [[String:AnyObject]],
            let dat = try? JSONSerialization.data(withJSONObject: arr, options: options),
            let str = String(data: dat, encoding: String.Encoding.utf8) {
            return str
        }
        return "[]"
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let arrayOfDictionaries = [
  { "abc": 123, "def": "ggg", "xyz": true },
  { "abc": 456, "def": "hhh", "xyz": false },
  { "abc": 789, "def": "jjj", "xyz": true }
]

print(arrayOfDictionaries.toJSONString())
Run Code Online (Sandbox Code Playgroud)


aya*_*aio 8

实现这一目标的一种简单方法是只扩展CollectionType.

使用可选的绑定和向下转换,然后序列化为数据,然后转换为字符串.

extension CollectionType where Generator.Element == [String:AnyObject] {
    func toJSONString(options: NSJSONWritingOptions = .PrettyPrinted) -> String {
        if let arr = self as? [[String:AnyObject]],
            let dat = try? NSJSONSerialization.dataWithJSONObject(arr, options: options),
            let str = String(data: dat, encoding: NSUTF8StringEncoding) {
            return str
        }
        return "[]"
    }
}

let arrayOfDictionaries: [[String:AnyObject]] = [
    ["abc":123, "def": "ggg", "xyz": true],
    ["abc":456, "def": "hhh", "xyz": false]
]

print(arrayOfDictionaries.toJSONString())
Run Code Online (Sandbox Code Playgroud)

输出:

[
  {
    "abc" : 123,
    "def" : "ggg",
    "xyz" : true
  },
  {
    "abc" : 456,
    "def" : "hhh",
    "xyz" : false
  }
]
Run Code Online (Sandbox Code Playgroud)