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