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

s5a0g9ez  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(250)

我想把一个字典数组转换成JSON格式。我的对象类型是[[String: AnyObject]],最后得到一个如下的例子:

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

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

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

我该怎么做?

fgw7neuy

fgw7neuy1#

实现这一点的一个简单方法是只扩展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())

输出量:

[
  {
    "abc" : 123,
    "def" : "ggg",
    "xyz" : true
  },
  {
    "abc" : 456,
    "def" : "hhh",
    "xyz" : false
  }
]
waxmsbnn

waxmsbnn2#

雨燕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 "[]"
    }
}

用法:

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

print(arrayOfDictionaries.toJSONString())
3npbholx

3npbholx3#

Swift 5,我不得不将其更改为Any而不是AnyObject,构建了Eric和A.G.的解决方案。

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

用法:

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

print(arrayOfDictionaries.toJSONString())
dba5bblo

dba5bblo4#

我认为您尝试扩展Array是不走运的,因为在扩展实体时,相同类型的要求是不可能的。
你可以做的就是利用免费函数:

func jsonify(array: [[String:AnyObject]]) { 
...
}

通过这种方式,您可以保持所需的类型安全,但代价是移动函数的位置。

相关问题