Skip to content

Instantly share code, notes, and snippets.

@meshileya
Forked from santoshrajan/JSONStringify.swift
Created September 6, 2020 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meshileya/ec9a0bd8d57f2436bdfca95b13c05603 to your computer and use it in GitHub Desktop.
Save meshileya/ec9a0bd8d57f2436bdfca95b13c05603 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