-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArrayType.swift
More file actions
125 lines (97 loc) · 3.04 KB
/
ArrayType.swift
File metadata and controls
125 lines (97 loc) · 3.04 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
//
// Viewer.swift
// BooKingForUser
//
// Created by Bobson on 2016/7/21.
// Copyright © 2016年 Bobson. All rights reserved.
//
import Foundation
import CoreGraphics
public protocol ArrayType
{
var arrayGenericType: Any { get }
func getJsonSerializableArray() -> [JsonSerializeable]?
func toJsonArray() -> Array<Any>
func toJsonData(_ options: JSONSerialization.WritingOptions) -> Data?
func toJsonString(_ options: JSONSerialization.WritingOptions) -> String
}
extension Array where Element: JsonDeserializeable
{
public init(jsonArray: JsonArray?)
{
self.init()
guard let jsonArray = jsonArray else {
return
}
deserialize(jsonArray: jsonArray)
}
public init(jsonString: String?)
{
self.init()
guard let data = jsonString?.data(using: .utf8) else {
return
}
guard let jsonDictionary = try? JSONSerialization.jsonObject(with: data, options: []) else {
return
}
guard let jsonArray = jsonDictionary as? JsonArray else {
return
}
deserialize(jsonArray: jsonArray)
}
private mutating func deserialize(jsonArray: JsonArray) {
for jsonDictionary in jsonArray
{
self.append(Element(jsonDictionary: jsonDictionary))
}
}
}
extension Array: ArrayType
{
public var arrayGenericType: Any {
return Element.self
}
public func getJsonSerializableArray() -> [JsonSerializeable]? {
var array: [JsonSerializeable] = []
for item in self {
switch item {
case _ as String,
_ as Bool,
_ as Int,
_ as Double,
_ as CGFloat:
return nil
case let item as JsonSerializeable:
array.append(item)
default:
return nil
}
}
return array
}
public func toJsonArray() -> Array<Any>
{
guard let array = self.getJsonSerializableArray() else
{
return self
}
var jsonArray: Array<Any> = []
for jsonSerializeable in array {
jsonArray.append(jsonSerializeable.toDictionary())
}
return jsonArray
}
public func toJsonData(_ options: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions()) -> Data?
{
let jsonArray = toJsonArray()
let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: options)
return data
}
public func toJsonString(_ options: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions()) -> String
{
guard let data = toJsonData(options) else {
return "{}"
}
return String(data: data, encoding: String.Encoding.utf8) ?? "{}"
}
}