How do you convert an array to a JSON string in swift? Basically I have a textfield with a button embedded in it. When button is pressed, the textfield text is added unto the testArray
. Furthermore, I want to convert this array to a JSON string.
This is what I have tried:
func addButtonPressed() { if goalsTextField.text == "" { // Do nothing } else { testArray.append(goalsTextField.text) goalsTableView.reloadData() saveDatatoDictionary() } } func saveDatatoDictionary() { data = NSKeyedArchiver.archivedDataWithRootObject(testArray) newData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(), error: nil) as? NSData string = NSString(data: newData!, encoding: NSUTF8StringEncoding) println(string) }
I would also like to return the JSON string using my savetoDictionart()
method.
As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.
As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.
Instead just do the array->data->string parts:
Swift 3/4
let array = [ "one", "two" ] func json(from object:Any) -> String? { guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { return nil } return String(data: data, encoding: String.Encoding.utf8) } print("\(json(from:array as Any))")
Original Answer
let array = [ "one", "two" ] let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil) let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
although you should probably not use forced unwrapping, it gives you the right starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With