How can I convert an array to string in swift?

Fatih Mustafa

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.

fphilipe

This should do:

"\(myArray.map { "\($0)" })"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I convert an Int array into a String? array in Swift

How do I convert a Swift Array to a String?

How can I convert a String to a char array?

How can I convert string to a array?

How can I convert string to array in JavaScript?

How can I use Lambda to convert a String array to Integer array?

How can I convert an array of string arrays into an array of objects?

How can i convert json array in string format into array[]

How I can convert int to binary string swift?

How can I convert a string in a textfield to an Int in Swift?

How to convert a NSUSerdefaults AnyObject? to SWIFT Array so that I can append to it?

How can I parse JSON to convert this to an array of objects in Swift?

How can I convert an array with custom classes to JSON in swift 3

How can I convert a Firebase Database Snapshot into an Array List in Swift?

How can I convert UIImage to Byte Array In Swift 4

How can I convert an array into a comma separated string?

How can I convert my circular array into a String?

How can i convert an array in Json string to c# object?

How can I convert CharArray / Array<Char> to a String?

How can I convert a json string to a json array using Newtonsoft?

How can I convert a comma-separated string to an array?

How can I convert a hex string to a byte array?

How can I convert a zero-terminated byte array to string?

How can I convert string to array of objects in JavaScript

How can I convert a string to JSON and save the data in an array?

How can I convert String into array of characters in java

How can I convert array to string in hive sql?

How can I convert a string of numbers to an array or vector of integers in Rust?

In Perl, how can I convert an array of bytes to a Unicode string?