Skip to content

Instantly share code, notes, and snippets.

@netgfx
Forked from santoshrajan/JSONStringify.swift
Created April 24, 2017 17:08
Show Gist options
  • Save netgfx/e0e007690dea21b78b1194d67da4551a to your computer and use it in GitHub Desktop.
Save netgfx/e0e007690dea21b78b1194d67da4551a to your computer and use it in GitHub Desktop.
JSON Stringify in Swift
// 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