Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
public protocol JSONStringConvertible: class {
var jsonString: String { get }
}
extension Logger {
// Converts an arbitrary object into some that is JSON-safe
static func makeJSONObject(_ object: Any) -> Any {
if let jsonObj = object as? JSONStringConvertible {
return jsonObj.jsonString
}
// Fragments are legal, so start by putting it in an array
if JSONSerialization.isValidJSONObject([object]) {
return object
}
switch object {
case let dict as [String: Any]:
var jsonDict: [String: Any] = [:]
for (key, value) in dict {
jsonDict[key] = makeJSONObject(value)
}
return jsonDict
case let dict as NSDictionary:
var jsonDict: [String: Any] = [:]
for (key, value) in dict {
jsonDict["\(key)"] = makeJSONObject(value)
}
return jsonDict
case let array as [Any]:
return array.map(makeJSONObject)
default:
return "\(object)"
}
}
// Converts an arbitrary (NSDictionary-safe) dictionary into a JSON string.
static func makeJSONString(_ dictionary: [String: Any]) -> String {
do {
return String(
data: try JSONSerialization.data(withJSONObject: makeJSONObject(dictionary), options: []),
encoding: String.Encoding.utf8)!
.replacingOccurrences(of: "\\/", with: "/") // NSJSONSerialization quotes forward slashes when it doesn't need to
} catch {
Swift.assertionFailure("Could not convert JSON: \(error)") // Do not use Log.* methods. We're inside of Log.
return ""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.