I want to convert an array to string like this
let myArray:[Any] = ["element 1", "element 2", ["element 3.1", "element 3.2"], "element 4"]
to
let convertedString = "[\"element 1\",\"element 2\",\"[\\\"element 3.1\\\",\\\"element 3.2\\\"]\",\"element 4\"]"
I have tried this
do {
let jsonData: Data = try JSONSerialization.data(withJSONObject: myArray, options: [])
if let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) {
print(jsonString)
}
} catch let error as NSError {
print("Array convertIntoJSON - \(error.description)")
}
However I get this result
["element 1","element 2",["element 3.1","element 3.2"],"element 4"]
I have done this in java by using JSONArray. I just call toString method to do this in java. I need to get third element as a string like given example above.
This should do:
"\(myArray.map { "\($0)" })"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments