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" | |
} | |
] | |
*/ | |
Swift 4
I end up using this version
enum StringifyError: Error {
case isNotValidJSONObject
}
struct JSONStringify {
let value: Any
func stringify(prettyPrinted: Bool = false) throws -> String {
let options: JSONSerialization.WritingOptions = prettyPrinted ? .prettyPrinted : .init(rawValue: 0)
if JSONSerialization.isValidJSONObject(self.value) {
let data = try JSONSerialization.data(withJSONObject: self.value, options: options)
if let string = String(data: data, encoding: .utf8) {
return string
}
}
throw StringifyError.isNotValidJSONObject
}
}
protocol Stringifiable {
func stringify(prettyPrinted: Bool) throws -> String
}
extension Stringifiable {
func stringify(prettyPrinted: Bool = false) throws -> String {
return try JSONStringify(value: self).stringify(prettyPrinted: prettyPrinted)
}
}
extension Dictionary: Stringifiable {}
extension Array: Stringifiable {}
//Usage:
do {
let stringified = try JSONStringify(value: ["name":"bob", "age":29]).stringify()
print(stringified)
} catch let error { print(error) }
//Or
let dictionary = ["name":"bob", "age":29] as [String: Any]
let stringifiedDictionary = try dictionary.stringify()
let array = ["name","bob", "age",29] as [Any]
let stringifiedArray = try array.stringify()
print(stringifiedDictionary)
print(stringifiedArray)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this version for Swift 3.x