Convert a dictionary to JSON in Swift


Swift provides a class called JSONSerialization to convert a dictionary to a JSON string. We will use the two steps to convert a dictionary to a JSON string in the Swift language. Here are the steps −

  • Convert a dictionary into JSON data format using JSONSerialization.data() method which takes a dictionary object as a parameter along with the options.

  • Now using the String(data:encoding:) constructor, convert the JSON data into JSON string format.

In this article, you will see some examples of how to convert a dictionary into a JSON string.

JSONSerialization

The Foundation framework for iOS and macOS includes a JSONSerialization class by default. To create a Swift dictionary or array, this class needs a string or data object. Using the same class, you can also turn a dictionary or an array into a JSON object. The serialization and deserialization procedures are handled by the JSONSerialization class.

Here is an Example of Converting a Dictionary into a JSON String

  • Step 1 − Create a global function that takes a dictionary as an argument to convert.

  • Step 2 − Using the data(withJSONObject:options:) method, convert a dictionary to JSON data format.

  • Step 3 − Handle the failure case in this method as the data() method returns an optional data value.

  • Step 4 − Convert the JSON data into JSON string using the String(data:encoding) method.

  • Step 5 − Handle the failure case as this method returns an optional string value.

import Foundation
func convertDictionaryToJSON(_ dictionary: [String: Any]) -> String? {

   guard let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) else {
      print("Something is wrong while converting dictionary to JSON data.")
      return nil
   }

   guard let jsonString = String(data: jsonData, encoding: .utf8) else {
      print("Something is wrong while converting JSON data to JSON string.")
      return nil
   }

   return jsonString
}
let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
if let output = convertDictionaryToJSON(dictionary) {
   print("Input dictionary: \(dictionary)")
   print("Output JSON: \(output)")
}

Output

Input dictionary: ["age": 32, "name": "John Allen", "company": "Google Inc."]
Output JSON: {
   "age" : 32,
   "name" : "John Allen",
   "company" : "Google Inc."
}

Note that if the dictionary contains values that cannot be converted to JSON, such as custom objects or circular references, the data(withJSONObject:options:) method will throw an error and the code inside the do-try-catch block will not be executed

Using an Extension

There is another approach that is highly recommended to convert a dictionary into a JSON string. You can create an extension and add these functions to that extension. It will help to access these properties and methods globally in your codebase. Here is an example of how to use an extension.

Extension

import Foundation
extension Dictionary {
       
   var jsonData: Data? {
      return try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
   }
       
   func toJSONString() -> String? {
      if let jsonData = jsonData {
         let jsonString = String(data: jsonData, encoding: .utf8)
         return jsonString
      }
      return nil
   }
}

Usage

func convertDictionaryToJSON() {
       
   let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
   guard let jsonData = dictionary.jsonData else {
      print("Something is wrong while converting dictionary to JSON data.")
      return
   }
   guard let jsonString = dictionary.toJSONString() else {
      print("Something is wrong while converting JSON data to JSON string.")
      return
   }
   print("Input dictionary: \(dictionary)")
   print("Output JSON: \(jsonString)")
}
convertDictionaryToJSON()

Output

Input dictionary: ["age": 32, "company": "Google Inc.", "name": "John Allen"]
Output JSON: {"age" : 32, "company" : "Google Inc.", "name" : "John Allen"}

Conclusion

In Swift, you are able to convert raw JSON data into collections like arrays or dictionaries via a low-level API. You can use the JSONSerialization class to convert the raw JSON object into meaningful objects. This class is in-built into the Foundation framework. You can use this class on any platform such as iOS, macOS, watchOS, etc. Also, in reverse order, you can convert your custom objects back into raw JSON data using the deserialization process.

In Swift 4, Apple introduced the Codable protocol which makes the serialization and deserialization process easy. This protocol provides a flexible way to use JSON data to parse and store the data into model class/struct. This protocol can be used to convert the model object into JSON data easily.

The Codable protocol helps to reduce the code and handle the process of serialization and deserialization, making the code more concise and maintainable.

Updated on: 04-Apr-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements