62 lines
1.4 KiB
Swift
62 lines
1.4 KiB
Swift
|
//
|
||
|
// Serializable.swift
|
||
|
// PSCB-OOS-iOS
|
||
|
//
|
||
|
// Created by OA on 16.10.2020.
|
||
|
//
|
||
|
|
||
|
import Foundation
|
||
|
|
||
|
// MARK: - Serializable
|
||
|
|
||
|
public protocol Serializable {
|
||
|
|
||
|
/// Serializes current object to generic JSON-Like dictionary
|
||
|
func serializeToJSON() -> JSONDict
|
||
|
|
||
|
}
|
||
|
|
||
|
// MARK: - Extension
|
||
|
|
||
|
public extension Serializable {
|
||
|
|
||
|
/// Serializes current object to data
|
||
|
func serializeToData() throws -> Data {
|
||
|
// let encoder = JSONEncoder()
|
||
|
// let data = try encoder.encode(self.serializeToJSON())
|
||
|
//
|
||
|
// return data
|
||
|
return try JSONSerialization.data(
|
||
|
withJSONObject: self.serializeToJSON(),
|
||
|
options: []
|
||
|
)
|
||
|
}
|
||
|
|
||
|
/// Serialzes to JSON-String
|
||
|
func serializeToString() throws -> String {
|
||
|
let data = try self.serializeToData()
|
||
|
return String(data: data, encoding: .utf8)!
|
||
|
}
|
||
|
|
||
|
/// Used for checking purposes if this object can be serialized without exception
|
||
|
func assumeSerializes() throws {
|
||
|
try serializeToString()
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
// MARK: - JSONDict
|
||
|
|
||
|
public typealias JSONDict = [AnyHashable: AnyHashable]
|
||
|
|
||
|
//extension JSONDict {
|
||
|
//
|
||
|
// public mutating func add<T: RawRepresentable>(key: T, nullable value: JSONDict.Value?) where T.RawValue == JSONDict.Key {
|
||
|
// if let value = value {
|
||
|
// self.updateValue(value, forKey: key.rawValue)
|
||
|
// }
|
||
|
// }
|
||
|
//
|
||
|
//}
|
||
|
|