28 lines
793 B
Swift
28 lines
793 B
Swift
import Foundation
|
|
|
|
public protocol AnyEncoder {
|
|
func encode<T: Encodable>(_ value: T) throws -> Data
|
|
}
|
|
|
|
extension JSONEncoder: AnyEncoder {}
|
|
extension PropertyListEncoder: AnyEncoder {}
|
|
|
|
extension Encodable {
|
|
public func encode(using encoder: AnyEncoder = JSONEncoder()) throws -> Data {
|
|
return try encoder.encode(self)
|
|
}
|
|
|
|
public func toJSON() -> JSONObject? {
|
|
guard let data = try? encode() else { return nil }
|
|
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? JSONObject }
|
|
}
|
|
|
|
public func toJSONString() -> String? {
|
|
guard let data = try? encode(),
|
|
let string = String(data: data, encoding: .utf8) else {
|
|
return nil
|
|
}
|
|
return string
|
|
}
|
|
}
|