2

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.

1 Answer 1

2

This should do:

"\(myArray.map { "\($0)" })"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.