Convert an array into a JSON string
suggest changePass an array of Any. The function returns a JSON string, or nil if the array is not valid JSON. A JSON string is a common request body for a web service.
let array = [["one" : 1], ["two" : 2], ["three" : 3], ["four" : 4]]
let jsonString = convertIntoJSONString(arrayObject: array)
print("jsonString - \(String(describing: jsonString))")
func convertIntoJSONString(arrayObject: [Any]) -> String? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: arrayObject, options: [])
return String(data: jsonData, encoding: .utf8)
} catch {
print("Array convertIntoJSON - \(error)")
return nil
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents