How to convert array of dictionary to JSON?

后端 未结 3 1599
离开以前
离开以前 2020-12-19 06:13

I have an array of dictionaries that I\'d like to convert to JSON. My object is of type [[String: AnyObject]] and would like to end up with a sample like this:<

相关标签:
3条回答
  • 2020-12-19 06:51

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

    Usage:

    let arrayOfDictionaries = [
      { "abc": 123, "def": "ggg", "xyz": true },
      { "abc": 456, "def": "hhh", "xyz": false },
      { "abc": 789, "def": "jjj", "xyz": true }
    ]
    
    print(arrayOfDictionaries.toJSONString())
    
    0 讨论(0)
  • 2020-12-19 07:03

    A simple way to achieve that is to just extend CollectionType.

    Use optional binding and downcasting, then serialize to data, then convert to string.

    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())
    

    Output:

    [
      {
        "abc" : 123,
        "def" : "ggg",
        "xyz" : true
      },
      {
        "abc" : 456,
        "def" : "hhh",
        "xyz" : false
      }
    ]
    
    0 讨论(0)
  • I think you're out of luck trying to extend Array, because same-type requirements are not possible when extending an entity.

    What you can make is to make use of free functions:

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

    This way you'll keep the type safety you want to, with the expense of moving the function location.

    0 讨论(0)
提交回复
热议问题