Created
October 12, 2014 05:36
-
-
Save santoshrajan/97aa46871cde0c0cb8a8 to your computer and use it in GitHub Desktop.
JSON Stringify in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author - Santosh Rajan | |
import Foundation | |
let jsonObject: [AnyObject] = [ | |
["name": "John", "age": 21], | |
["name": "Bob", "age": 35], | |
] | |
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 "" | |
} | |
/* | |
* Usage | |
*/ | |
let jsonString = JSONStringify(jsonObject) | |
println(jsonString) | |
// Prints - [{"age":21,"name":"John"},{"age":35,"name":"Bob"}] | |
/* | |
* Usage - Pretty Printed | |
*/ | |
let jsonStringPretty = JSONStringify(jsonObject, prettyPrinted: true) | |
println(jsonStringPretty) | |
/* Prints the following - | |
[ | |
{ | |
"age" : 21, | |
"name" : "John" | |
}, | |
{ | |
"age" : 35, | |
"name" : "Bob" | |
} | |
] | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 4
I end up using this version