convert array to json in swift

To convert an array to JSON in Swift, you need to encode the array using JSONEncoder. Here is an example:

main.swift
let array = [1, 2, 3, 4]
do {
    let jsonData = try JSONEncoder().encode(array)
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
} catch {
    print("Error encoding array to JSON: \(error.localizedDescription)")
}
264 chars
10 lines

In the code above, we create an array of integers and encode it using JSONEncoder. The encoded data is then converted to a string using String(data:encoding:) method. Finally, the string is printed to the console.

To decode a JSON string back to an array, you can use JSONDecoder. Here's an example:

main.swift
let jsonString = "[1,2,3,4]"
if let jsonData = jsonString.data(using: .utf8) {
    do {
        let decodedArray = try JSONDecoder().decode([Int].self, from: jsonData)
        print(decodedArray)
    } catch {
        print("Error decoding JSON to array: \(error.localizedDescription)")
    }
}
295 chars
10 lines

In the code above, we create a JSON string and convert it to Data. We then decode the Data using JSONDecoder and print the resulting array to the console.

gistlibby LogSnag