Convert Dictionary to JSON in Swift Convert Dictionary to JSON in Swift json json

Convert Dictionary to JSON in Swift


Swift 3.0

With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

let dic = ["2": "B", "1": "A", "3": "C"]do {    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)    // here "jsonData" is the dictionary encoded in JSON data    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])    // here "decoded" is of type `Any`, decoded from JSON data    // you can now cast it with the right type            if let dictFromJSON = decoded as? [String:String] {        // use dictFromJSON    }} catch {    print(error.localizedDescription)}

Swift 2.x

do {    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)    // here "jsonData" is the dictionary encoded in JSON data    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])    // here "decoded" is of type `AnyObject`, decoded from JSON data    // you can now cast it with the right type     if let dictFromJSON = decoded as? [String:String] {        // use dictFromJSON    }} catch let error as NSError {    print(error)}

Swift 1

var error: NSError?if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {    if error != nil {        println(error)    } else {        // here "jsonData" is the dictionary encoded in JSON data    }}if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {    if error != nil {        println(error)    } else {        // here "decoded" is the dictionary decoded from JSON data    }}


You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.

Here is example code that will convert a dictionary of strings to JSON:

Swift 3 version:

import Foundationlet dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]if let theJSONData = try? JSONSerialization.data(    withJSONObject: dictionary,    options: []) {    let theJSONText = String(data: theJSONData,                               encoding: .ascii)    print("JSON string = \(theJSONText!)")}

To display the above in "pretty printed" format you'd change the options line to:

    options: [.prettyPrinted]

Or in Swift 2 syntax:

import Foundation let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]let theJSONData = NSJSONSerialization.dataWithJSONObject(  dictionary ,  options: NSJSONWritingOptions(0),  error: nil)let theJSONText = NSString(data: theJSONData!,  encoding: NSASCIIStringEncoding)println("JSON string = \(theJSONText!)")

The output of that is

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"

Or in pretty format:

{  "anotherKey" : "anotherValue",  "aKey" : "aValue"}

The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.

EDIT:

In Swift 3/4 syntax, the code above looks like this:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]    if let theJSONData = try?  JSONSerialization.data(      withJSONObject: dictionary,      options: .prettyPrinted      ),      let theJSONText = String(data: theJSONData,                               encoding: String.Encoding.ascii) {          print("JSON string = \n\(theJSONText)")    }  }


Swift 5:

let dic = ["2": "B", "1": "A", "3": "C"]let encoder = JSONEncoder()if let jsonData = try? encoder.encode(dic) {    if let jsonString = String(data: jsonData, encoding: .utf8) {        print(jsonString)    }}

Note that keys and values must implement Codable. Strings, Ints, and Doubles (and more) are already Codable. See Encoding and Decoding Custom Types.

Also note: As mentioned in a comment, Any does not conform to Codable. It is likely still a good approach to adapt your data to become Codable so that you are making use of Swift typing (especially in the case that you are also going to decode any encoded json), and so that you can be more declarative about the outcome of your encoding.