Last active
August 29, 2015 14:23
-
-
Save jaisontj/ced446084bf652992c7a to your computer and use it in GitHub Desktop.
Groundup 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
func jsonStringify(jsonObject: AnyObject) -> String { | |
var jsonString: String = "" | |
switch jsonObject { | |
case _ as [String: AnyObject] : | |
let tempObject: [String: AnyObject] = jsonObject as! [String: AnyObject] | |
jsonString += "{" | |
for (key , value) in tempObject { | |
if jsonString.characters.count > 1 { | |
jsonString += "," | |
} | |
jsonString += "\"" + String(key) + "\":" | |
jsonString += jsonStringify(value) | |
} | |
jsonString += "}" | |
case _ as [AnyObject] : | |
jsonString += "[" | |
for i in 0..<jsonObject.count { | |
if i > 0 { | |
jsonString += "," | |
} | |
jsonString += jsonStringify(jsonObject[i]) | |
} | |
jsonString += "]" | |
case _ as String : | |
jsonString += ("\"" + String(jsonObject) + "\"") | |
case _ as NSNumber : | |
if jsonObject.isEqualToValue(NSNumber(bool: true)) { | |
jsonString += "true" | |
} else if jsonObject.isEqualToValue(NSNumber(bool: false)) { | |
jsonString += "false" | |
} else { | |
return String(jsonObject) | |
} | |
case _ as NULL : | |
jsonString += "null" | |
default : | |
jsonString += "" | |
} | |
return jsonString | |
} | |
/* USAGE | |
var stringifiedJsonObject = jsonStringify(jsonObject) */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment