Skip to content

Instantly share code, notes, and snippets.

@chuthan20
Created March 10, 2016 03:42
Show Gist options
  • Save chuthan20/4ab4c784fe8ef264ba1a to your computer and use it in GitHub Desktop.
Save chuthan20/4ab4c784fe8ef264ba1a to your computer and use it in GitHub Desktop.
Wrapping NSJSONSerialization to make the methods simpler/easy to use.
//: Playground - noun: a place where people can play
import Foundation
public class JSON {
public static func toNSData(obj: AnyObject) -> NSData? {
return try? NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions(rawValue: 0))
}
public static func toJSONObj(obj: NSData) -> AnyObject? {
return try? NSJSONSerialization.JSONObjectWithData(obj, options: NSJSONReadingOptions(rawValue: 0))
}
private static func fromJSONObj(type: AnyObject) -> AnyObject? {
if let type = type as? NSData, tempJSON = toJSONObj(type) {
return tempJSON
} else if let type = type as? String, data = type.dataUsingEncoding(NSUTF8StringEncoding) {
return fromJSONObj(data)
}
return nil
}
public static func toJSONDict(type: AnyObject) -> [String:AnyObject]? {
return fromJSONObj(type) as? [String:AnyObject]
}
public static func toJSONArray(type: AnyObject) -> [AnyObject]? {
return fromJSONObj(type) as? [AnyObject]
}
public static func toJSONString(type: AnyObject) -> String? {
if let type = type as? String {
return type
} else if let type = type as? [String:AnyObject],
anyJSON = toNSData(type) {
return String(data: anyJSON, encoding: NSUTF8StringEncoding)
} else if let type = type as? [AnyObject],
anyJSON = toNSData(type) {
return String(data: anyJSON, encoding: NSUTF8StringEncoding)
} else if let type = type as? NSData {
return String(data: type, encoding: NSUTF8StringEncoding)
}
return nil
}
}
// usage
let dict = ["boo":"foo", "moo":"lo"]
let str = JSON.toJSONString(dict)
let data = JSON.toJSONDict(str!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment