1

This might be an easy question, but how can I create a simple JSON String from an existing Array?

In the Documentation the only thing I found is:

class func JSONObjectWithData(_ data: NSData,
                  options opt: NSJSONReadingOptions,
                    error error: NSErrorPointer) -> AnyObject?

But I only want to create a simple JSON String from an existing Array.

With the existing Swift JSON Extensions I am only able to parse existing JSON Strings, and could not create a new String.

I could manually create the String, but there might be a better solution.

Any help would be greatly appreciated.

2 Answers 2

3

If you have a NSArray object, you could create your JSON String by using something like:

func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
    var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil
    if NSJSONSerialization.isValidJSONObject(value) {
        if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) {
            if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
                return string
            }
        }
    }
    return ""
}

I found here the details for this function.

SWIFT 3

 func JSON2String(jsonObj: AnyObject, prettyPrinted: Bool = false) -> String {
    let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : []
    if JSONSerialization.isValidJSONObject(jsonObj) {
        if let data = try? JSONSerialization.data(withJSONObject: jsonObj, options: options) {
            if let string = String(data: data, encoding: Task.StringEncoding) {
                return string
            }
        }
    }
    return ""
}
Sign up to request clarification or add additional context in comments.

Comments

1

Let's say you have an array of Strings called array. You would do this:

let array = [ "String1", "String2" ]
var error:NSError?

let data = NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions.allZeros, error: &error)
let str = NSString(data:data!, encoding:NSUTF8StringEncoding)

println("\(str!)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.