Guest User

Untitled

a guest
Jul 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. protocol JSONRepresentation{
  2. func to_json() -> String
  3. }
  4.  
  5. extension JSONRepresentation{
  6. func to_json() -> String
  7. {
  8. let reflection = Mirror(reflecting: self)
  9. let root = String(describing: reflection.subjectType).lowercased()
  10. var children :[String:Any] = [:]
  11. reflection.children.forEach { (child) in
  12. children[child.label!] = child.value
  13. }
  14. let hash = [
  15. root:children
  16. ]
  17. let jsonData = try! JSONSerialization.data(withJSONObject: hash, options: .prettyPrinted)
  18. let json = String(bytes: jsonData, encoding: .utf8)!
  19. return json
  20.  
  21. }
  22.  
  23. }
Add Comment
Please, Sign In to add comment