Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to JSON string in swift

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.

like image 805
DrPatience Avatar asked Feb 04 '15 15:02

DrPatience


1 Answers

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.

like image 103
David Berry Avatar answered Sep 18 '22 22:09

David Berry