-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathJSONEncodable.swift
More file actions
317 lines (284 loc) · 10.1 KB
/
JSONEncodable.swift
File metadata and controls
317 lines (284 loc) · 10.1 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//
// JSONEncodable.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Encoding Errors
public enum JSONEncodableError: ErrorProtocol, CustomStringConvertible {
case incompatibleTypeError(
elementType: Any.Type
)
case arrayIncompatibleTypeError(
elementType: Any.Type
)
case dictionaryIncompatibleTypeError(
elementType: Any.Type
)
case childIncompatibleTypeError(
key: String,
elementType: Any.Type
)
case transformerFailedError(
key: String
)
public var description: String {
switch self {
case let .incompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Incompatible type \(elementType)"
case let .arrayIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an array of incompatible type \(elementType)"
case let .dictionaryIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an dictionary of incompatible type \(elementType)"
case let .childIncompatibleTypeError(key: key, elementType: elementType):
return "JSONEncodableError: Got incompatible type \(elementType) for key \(key)"
case let .transformerFailedError(key: key):
return "JSONEncodableError: Transformer failed for key \(key)"
}
}
}
// Struct -> Dictionary
public protocol JSONEncodable {
func toJSON() throws -> AnyObject
}
public extension JSONEncodable {
func toJSON() throws -> AnyObject {
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle where style == .`struct` || style == .`class` else {
throw JSONEncodableError.incompatibleTypeError(elementType: self.dynamicType)
}
return try JSONEncoder.create({ (encoder) -> Void in
// loop through all properties (instance variables)
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
let value: Any
// unwrap optionals
if let v = valueMaybe as? JSONOptional {
guard let unwrapped = v.wrapped else {
continue
}
value = unwrapped
}
else {
value = valueMaybe
}
switch (value) {
case let value as JSONEncodable:
try encoder.encode(value, key: label)
case let value as JSONArray:
try encoder.encode(value, key: label)
case let value as JSONDictionary:
try encoder.encode(value, key: label)
default:
throw JSONEncodableError.childIncompatibleTypeError(key: label, elementType: value.dynamicType)
}
}
})
}
}
public extension Array {//where Element: JSONEncodable {
private var wrapped: [Any] { return self.map{$0} }
public func toJSON() throws -> AnyObject {
var results: [AnyObject] = []
for item in self.wrapped {
if let item = item as? JSONEncodable {
results.append(try item.toJSON())
}
else {
throw JSONEncodableError.arrayIncompatibleTypeError(elementType: item.dynamicType)
}
}
return results
}
}
// Dictionary convenience methods
public extension Dictionary {//where Key: String, Value: JSONEncodable {
public func toJSON() throws -> AnyObject {
var result: [String: AnyObject] = [:]
for (k, item) in self {
if let item = item as? JSONEncodable {
result[String(k)] = try item.toJSON()
}
else {
throw JSONEncodableError.dictionaryIncompatibleTypeError(elementType: item.dynamicType)
}
}
return result
}
}
// JSONEncoder - provides utility methods for encoding
public class JSONEncoder {
var object = JSONObject()
public static func create(_ setup: @noescape (encoder: JSONEncoder) throws -> Void) rethrows -> JSONObject {
let encoder = JSONEncoder()
try setup(encoder: encoder)
return encoder.object
}
private func update(object: JSONObject, keys: [String], value: AnyObject) -> JSONObject
{
var newObject = object
var newKeys = keys
let firstKey = newKeys.removeFirst()
if newKeys.count > 0 {
let innerObject = object[firstKey] as? JSONObject ?? JSONObject()
newObject[firstKey] = update(object: innerObject, keys: newKeys, value: value)
} else {
newObject[firstKey] = value
}
return newObject
}
/*
Note:
There is some duplication because methods with generic constraints need to
take a concrete type conforming to the constraint are unable to take a parameter
typed to the protocol. Hence we need non-generic versions so we can cast from
Any to JSONEncodable in the default implementation for toJSON().
*/
// JSONEncodable
public func encode<Encodable: JSONEncodable>(_ value: Encodable, key: String) throws {
let result = try value.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
private func encode(_ value: JSONEncodable, key: String) throws {
let result = try value.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// JSONEncodable?
public func encode<Encodable: JSONEncodable>(_ value: Encodable?, key: String) throws {
guard let actual = value else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// Enum
public func encode<Enum: RawRepresentable>(_ value: Enum, key: String) throws {
guard let compatible = value.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// Enum?
public func encode<Enum: RawRepresentable>(_ value: Enum?, key: String) throws {
guard let actual = value else {
return
}
guard let compatible = actual.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [JSONEncodable]
public func encode<Encodable: JSONEncodable>(_ array: [Encodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
public func encode(_ array: [JSONEncodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
private func encode(_ array: JSONArray, key: String) throws {
guard array.count > 0 && array.elementsAreJSONEncodable() else {
return
}
let encodable = array.elementsMadeJSONEncodable()
let result = try encodable.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [JSONEncodable]?
public func encode<Encodable: JSONEncodable>(_ value: [Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [Enum]
public func encode<Enum: RawRepresentable>(_ value: [Enum], key: String) throws {
guard value.count > 0 else {
return
}
let result = try value.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [Enum]?
public func encode<Enum: RawRepresentable>(_ value: [Enum]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [String:JSONEncodable]
public func encode<Encodable: JSONEncodable>(_ dictionary: [String:Encodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
public func encode(_ dictionary: [String:JSONEncodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object[key] = result
}
private func encode(_ dictionary: JSONDictionary, key: String) throws {
guard dictionary.count > 0 && dictionary.valuesAreJSONEncodable() else {
return
}
let encodable = dictionary.valuesMadeJSONEncodable()
let result = try encodable.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [String:JSONEncodable]?
public func encode<Encodable: JSONEncodable>(_ value: [String:Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// JSONTransformable
public func encode<EncodedType, DecodedType>(_ value: DecodedType, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let result = transformer.encoding(value) else {
throw JSONEncodableError.transformerFailedError(key: key)
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result as! AnyObject)
}
// JSONTransformable?
public func encode<EncodedType, DecodedType>(_ value: DecodedType?, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let actual = value else {
return
}
guard let result = transformer.encoding(actual) else {
return
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result as! AnyObject)
}
}