-
-
Save netgfx/e0e007690dea21b78b1194d67da4551a to your computer and use it in GitHub Desktop.
JSON Stringify in Swift
This file contains 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