To convert a JSON string to a dictionary in Swift, you can use the `JSONSerialization` class. This allows you to parse a JSON string and convert it into a dictionary.
We can convert a JSON string to a dictionary in Swift using the `JSONSerialization` class. This example demonstrates how to declare a JSON string, use the `JSONSerialization.jsonObject(with:options:)` method to convert the JSON string to a dictionary, and print the resulting dictionary.
For example,
jsonString
that contains the JSON representation of a dictionary.import Foundation
let jsonString = "{\"1\":\"One\",\"2\":\"Two\",\"3\":\"Three\"}"
// Convert the JSON string to a dictionary using JSONSerialization
if let jsonData = jsonString.data(using: .utf8),
let myDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: String] {
// Print the resulting dictionary
print("Dictionary from JSON string:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
}
Dictionary from JSON string: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can convert a JSON string with complex values to a dictionary in Swift using the `JSONSerialization` class. This example demonstrates how to declare a JSON string with complex values, use the `JSONSerialization.jsonObject(with:options:)` method to convert the JSON string to a dictionary, and print the resulting dictionary.
For example,
jsonString
that contains the JSON representation of a dictionary with complex values.import Foundation
let jsonString = "{\"1\":{\"name\":\"John\",\"age\":30},\"2\":{\"name\":\"Jane\",\"age\":25}}"
// Convert the JSON string to a dictionary using JSONSerialization
if let jsonData = jsonString.data(using: .utf8),
let myDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: [String: Any]] {
// Print the resulting dictionary
print("Dictionary from JSON string:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
}
Dictionary from JSON string: Key: 1, Value: {"name": "John", "age": 30} Key: 2, Value: {"name": "Jane", "age": 25}
In this tutorial, we learned How to Convert a JSON String to a Dictionary in Swift language with well detailed examples.