To convert a dictionary to a JSON string in Swift, you can use the `JSONSerialization` class. This allows you to create a JSON string representation of the dictionary.
We can convert a dictionary to a JSON string in Swift using the `JSONSerialization` class. This example demonstrates how to declare and initialize a dictionary, use the `JSONSerialization.data(withJSONObject:options:)` method to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
myDictionary
with integer keys and string values.import Foundation
let myDictionary: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
// Convert the dictionary to a JSON string using JSONSerialization
if let jsonData = try? JSONSerialization.data(withJSONObject: myDictionary, options: .prettyPrinted),
let jsonString = String(data: jsonData, encoding: .utf8) {
// Print the resulting JSON string
print("JSON string:")
print(jsonString)
}
JSON string: { "1" : "One", "2" : "Two", "3" : "Three" }
We can convert a dictionary with complex values to a JSON string in Swift using the `JSONSerialization` class. This example demonstrates how to declare and initialize a dictionary with complex values, use the `JSONSerialization.data(withJSONObject:options:)` method to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
myDictionary
with integer keys and values that are dictionaries.import Foundation
let myDictionary: [Int: [String: Any]] = [
1: ["name": "John", "age": 30],
2: ["name": "Jane", "age": 25]
]
// Convert the dictionary to a JSON string using JSONSerialization
if let jsonData = try? JSONSerialization.data(withJSONObject: myDictionary, options: .prettyPrinted),
let jsonString = String(data: jsonData, encoding: .utf8) {
// Print the resulting JSON string
print("JSON string:")
print(jsonString)
}
JSON string: { "1" : { "name" : "John", "age" : 30 }, "2" : { "name" : "Jane", "age" : 25 } }
In this tutorial, we learned How to Convert a Dictionary to a JSON String in Swift language with well detailed examples.