-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJSONSerialisable.swift
51 lines (41 loc) · 1.31 KB
/
JSONSerialisable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// JSONSerialisable.swift
// Slide the Box
//
// Created by Alex Morgan on 04/01/2017.
// Copyright © 2017 Alex Morgan. All rights reserved.
//
import Foundation
protocol JSONSerialisable: JSONRepresentable {
}
extension JSONSerialisable {
var JSONRepresentation: AnyObject {
var representation = [String: AnyObject]()
for case let (label?, value) in Mirror(reflecting: self).children {
switch value {
case let value as JSONRepresentable:
representation[label] = value.JSONRepresentation
case let value as NSObject:
representation[label] = value
default:
// Ignore any unserializable properties
break
}
}
return representation as AnyObject
}
}
extension JSONSerialisable {
func toJSON() -> String? {
let representation = JSONRepresentation
guard JSONSerialization.isValidJSONObject(representation) else {
return nil
}
do {
let data = try JSONSerialization.data(withJSONObject: representation, options: [])
return String(data: data, encoding: String.Encoding.utf8)
} catch {
return nil
}
}
}