JSON.swift 636 B

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // JSON.swift
  3. // FreeAPS
  4. //
  5. // Created by Ivan Valkou on 19.01.2021.
  6. //
  7. import Foundation
  8. protocol JSON: Codable {
  9. func toString() -> String
  10. init?(from: String)
  11. }
  12. extension JSON {
  13. func toString() -> String {
  14. String(data: try! JSONEncoder().encode(self), encoding: .utf8)!
  15. }
  16. init?(from: String) {
  17. guard let data = from.data(using: .utf8),
  18. let object = try? JSONDecoder().decode(Self.self, from: data) else {
  19. return nil
  20. }
  21. self = object
  22. }
  23. }
  24. extension String: JSON {
  25. func toString() -> String { self }
  26. init?(from: String) { self = from }
  27. }