/
Mapper.swift
executable file
·369 lines (291 loc) · 10.3 KB
/
Mapper.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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
// Copyright (c) 2014 hearst. All rights reserved.
//
import Foundation
public protocol Mappable {
init?(_ map: Map)
mutating func mapping(map: Map)
}
public enum MappingType {
case FromJSON
case ToJSON
}
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
var JSONDictionary: [String : AnyObject] = [:]
var currentValue: AnyObject?
var currentKey: String?
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
private init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
currentKey = key
// break down the components of the key
currentValue = valueFor(key.componentsSeparatedByString("."), JSONDictionary)
return self
}
// MARK: Immutable Mapping
public func value<T>() -> T? {
return currentValue as? T
}
public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T {
return value() ?? defaultValue()
}
/// Returns current JSON value of type `T` if it is existing, or returns a
/// unusable proxy value for `T` and collects failed count.
public func valueOrFail<T>() -> T {
if let value: T = value() {
return value
} else {
// Collects failed count
failedCount++
// Returns dummy memory as a proxy for type `T`
let pointer = UnsafeMutablePointer<T>.alloc(0)
pointer.dealloc(0)
return pointer.memory
}
}
/// Returns whether the receiver is success or failure.
public var isValid: Bool {
return failedCount == 0
}
}
/// Fetch value from JSON dictionary, loop through them until we reach the desired object.
private func valueFor(keyPathComponents: [String], dictionary: [String : AnyObject]) -> AnyObject? {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return nil
}
if let object: AnyObject = dictionary[keyPathComponents.first!] {
switch object {
case is NSNull:
return nil
case let dict as [String : AnyObject] where keyPathComponents.count > 1:
let tail = Array(keyPathComponents[1..<keyPathComponents.count])
return valueFor(tail, dict)
default:
return object
}
}
return nil
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public init(){
}
// MARK: Mapping functions that map to an existing object toObject
/// Map a JSON string onto an existing object
public func map(JSONString: String, var toObject object: N) -> N {
if let JSON = parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, var toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
object.mapping(map)
return object
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
if let string = JSONString as? String {
return map(string)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
let object = N(map)
return object
}
//MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N] {
let parsedJSON: AnyObject? = parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return []
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N] {
// map every element in JSON array to type N
return JSONArray.filterMap(map)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N] {
// map every value in dictionary to type N
return JSONDictionary.filterMap(map)
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]] {
// map every value in dictionary to type N
return JSONDictionary.filterMap({ mapArray($0) })
}
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(var object: N) -> [String : AnyObject] {
let map = Map(mappingType: .ToJSON, JSONDictionary: [:])
object.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string
public func toJSONString(object: N, prettyPrint: Bool) -> String? {
let JSONDict = toJSON(object)
var err: NSError?
if NSJSONSerialization.isValidJSONObject(JSONDict) {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : .allZeros
let JSONData: NSData? = NSJSONSerialization.dataWithJSONObject(JSONDict, options: options, error: &err)
if let error = err {
println(error)
}
if let JSON = JSONData {
return NSString(data: JSON, encoding: NSUTF8StringEncoding) as? String
}
}
return nil
}
// MARK: Private utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
private func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = parseJSONString(JSON)
return parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
private func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
if let JSONDict = JSON as? [String : AnyObject] {
return JSONDict
}
return nil
}
/// Convert a JSON String into an Object using NSJSONSerialization
private func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
var error: NSError?
let parsedJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
return parsedJSON
}
return nil
}
}
extension Array {
internal func filterMap<U>(@noescape f: T -> U?) -> [U] {
var mapped = [U]()
for value in self {
if let newValue = f(value) {
mapped.append(newValue)
}
}
return mapped
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
let newValue = f(value)
mapped[key] = newValue
}
return mapped
}
}