Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created October 16, 2019 19:32
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 rnapier/0055df017956702d8ed552a799c50357 to your computer and use it in GitHub Desktop.
Save rnapier/0055df017956702d8ed552a799c50357 to your computer and use it in GitHub Desktop.
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