In Swift, a JSON object is an instance of the Data
class, which is a binary representation of the JSON string, and arrays are one of the most used data structures. This succinct, example-based article will show you a couple of different ways to convert a given array to JSON.
Using JSONEncoder.encode() method
The JSONEncoder.encode(_:)
and String(data:encoding:)
of the Foundation
framework can convert an array that contains instances of a custom type that conforms to the Codable
protocol to a JSON data object and then to a JSON string, respectively.
Example:
import Foundation
// Define a custom type that conforms to Codable protocol
struct Person: Codable {
var name: String
var age: Int
}
// Create an array of Person objects
let array = [
Person(name: "Red Wolf", age: 99),
Person(name: "Ronaldo", age: 39),
Person(name: "Thanos", age: 200),
]
// Create an instance of JSONEncoder
let encoder = JSONEncoder()
// Convert array to JSON data
let data = try encoder.encode(array)
// Convert JSON data to JSON string
let string: String? = String(data: data, encoding: .utf8)
print(string!)
Output:
[{"name":"Red Wolf","age":99},{"name":"Ronaldo","age":39},{"name":"Thanos","age":200}]
Using JSONSerialization.data() method
An alternative solution is to use the built-in methodJSONSerialization.data(withJSONObject:options:)
of the Foundation
framework. It can convert an array that contains only JSON-encodable values (such as string, number, dictionary, array, or nil) to a JSON data object. You can turn this object into a JSON string by using the String(data:encoding:)
method.
You should use the try/catch
syntax to handle any potential errors that may occur during the conversion process as shown in the example below:
import Foundation
let myArray = ["Sling Academy", "Swift", "iOS", "Example"]
do {
// Convert array to JSON data
let data = try JSONSerialization.data(
withJSONObject: myArray,
options: []
)
// Convert JSON data to JSON string
let jsonString: String? = String(data: data, encoding: .utf8)
// Print JSON string
print(jsonString ?? "JSON string is nil")
} catch {
// Handle error
print(error.localizedDescription)
}
Output:
["Sling Academy","Swift","iOS","Example"]