Last active
March 30, 2021 07:16
-
-
Save SergLam/64090c90848df2074bb8c7aa5611f9c6 to your computer and use it in GitHub Desktop.
JSONAble - protocol for network models + send them in app custom Observation infrastructure
This file contains hidden or 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 | |
import Moya | |
typealias DataUpdateInfo = [AnyHashable: [String: Any]] | |
protocol JSONAble where Self: Codable { | |
func toJSON() -> [String: Any] | |
static func fromJSON(_ dictionary: [AnyHashable: Any]) -> Self? | |
func toMultipartData() -> [Moya.MultipartFormData]? | |
} | |
extension JSONAble { | |
func toJSON() -> [String: Any] { | |
let jsonEncoder = JSONEncoder() | |
if let jsonData = try? jsonEncoder.encode(self), | |
let jsonString = String(data: jsonData, encoding: String.Encoding.utf8), | |
let jsonDict = jsonString.toDictionary() { | |
return jsonDict | |
} | |
return [:] | |
} | |
static func fromJSON(_ dictionary: [AnyHashable: Any]) -> Self? { | |
if let data = try? JSONSerialization.data(withJSONObject: dictionary, options: []), | |
let result = try? fromData(data) { | |
return result | |
} | |
return nil | |
} | |
static func fromData(_ data: Data) throws -> Self { | |
let decoder = JSONDecoder() | |
do { | |
let object = try decoder.decode(Self.self, from: data) | |
return object | |
} catch { | |
print("Decode \(String(describing: self)) error") | |
throw error | |
} | |
} | |
} | |
extension JSONAble { | |
func toDataUpdate() -> DataUpdateInfo { | |
return [String(describing: Self.Type.self): self.toJSON()] | |
} | |
static func fromDataUpdate(_ data: DataUpdateInfo) -> Self? { | |
guard let dict = data[String(describing: Self.Type.self)] else { | |
return nil | |
} | |
return Self.fromJSON(dict) | |
} | |
} | |
extension String { | |
func toDictionary() -> [String: Any]? { | |
if let data = self.data(using: .utf8) { | |
do { | |
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] | |
return json | |
} catch { | |
print("Encode \(String(describing: self)) error") | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment