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.


Solution 1:

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.

Solution 2:

Swift 3.0 - 4.0 version

do {

    //Convert to Data
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryOrArray, options: JSONSerialization.WritingOptions.prettyPrinted)

    //Convert back to string. Usually only do this for debugging
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
       print(JSONString)
    }

    //In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [Any].
    var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]


} catch {
    print(error.description)
}

The JSONSerialization.WritingOptions.prettyPrinted option gives it to the eventual consumer in an easier to read format if they were to print it out in the debugger.

Reference: Apple Documentation

The JSONSerialization.ReadingOptions.mutableContainers option lets you mutate the returned array's and/or dictionaries.

Reference for all ReadingOptions: Apple Documentation

NOTE: Swift 4 has the ability to encode and decode your objects using a new protocol. Here is Apples Documentation, and a quick tutorial for a starting example.