How to convert a JSON string to a dictionary in Swift?


Swift provides a class called JSONSerialization to convert a JSON string to dictionary format. For example, you are receiving a JSON string from the database, in order to use it in the application, you might need to convert it into a real object type. In this article, you will see some examples of how to convert a JSON string into a dictionary.

What is JSON String?

A JSON string is a string that is converted to a different format such as base64 or URL encoding. This converted string can be used for networking requests or to store in the database. This converted string provides safety while sending in a request. Also, you can send image data in JSON string format.

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.

Example

In Swift, you can convert a JSON string to a dictionary using the JSONSerialization class. Here is an example code snippet −

let jsonString = "{"movies":[{"id": 100, "name": "Transformers", "desc": "Desc here."},{"id": 101, "name": "Avengers", "desc": "Desc here 2."},{"id": 102, "name": "Interstellar", "desc": "Desc here 3."}]}"
let data = Data(jsonString.utf8)
do {
   // make sure this JSON is in the format we expect
   if let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
      print("Dictionary format: \(dictionary)")
   }
} catch let error as NSError {
   print("Failed to load: \(error.localizedDescription)")
}

Output

Dictionary format: ["movies": <__NSArrayI 0x600000f3b3f0>(
   {
      desc = "Desc here.";
      id = 100;
      name = Transformers;
   },
   {
      desc = "Desc here 2.";
      id = 101;
      name = Avengers;
   },
   {
      desc = "Desc here 3.";
      id = 102;
      name = Interstellar;
   }
   )
]

In the above example, we create a JSON string with some basic information, convert it to dictionary format, and finally convert the JSON data to a dictionary. The options parameter in the jsonObject(with:options:) method is optional.

Note that if the JSON string contains values that cannot be converted to a dictionary, such as custom objects or circular references, the jsonObject(with: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 JSON string into a dictionary. 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.

Example

Here is an example of how to use an extension.

extension String {
    
   var toDictionary: [String: Any]? {
      let data = Data(self.utf8)
      do {
         // make sure this JSON is in the format we expect
         if let dictionary = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any] {
            return dictionary
         }
      } catch let error as NSError {
          print("Failed to load: \(error.localizedDescription)")
      }
      return nil
   }
}
let jsonString = "{"movies":[{"id": 100, "name": "Transformers", "desc": "Desc here."},{"id": 101, "name": "Avengers", "desc": "Desc here 2."},{"id": 102, "name": "Interstellar", "desc": "Desc here 3."}]}"
if let dictionary = jsonString.toDictionary {
   print("Dictionary format: \(dictionary)")
}

Output

Dictionary format: ["movies": <__NSArrayI 0x600001d63ab0>(
   {
      desc = "Desc here.";
      id = 100;
      name = Transformers;
   },
   {
      desc = "Desc here 2.";
      id = 101;
      name = Avengers;
   },
   {
      desc = "Desc here 3.";
      id = 102;
      name = Interstellar;
   }
   )
]

Conclusion

In Swift, you are able to convert raw JSON strings 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 string 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

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements