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
struct MyStruct: Codable {
let id: String
let regionsID: Int?
let created: Int
let modified: Int
let removed: Int?


enum CodingKeys: String, CodingKey, CaseIterable {
case id = "id"
case regionsID = "regions_id"
case created = "created"
case modified = "modified"
case removed = "removed"
}

var jsonDictionary: [String : Any] {
let mirror = Mirror(reflecting: self)
var dic = [String: Any]()
var counter = 0
for (name, value) in mirror.children {
let key = CodingKeys.allCases[counter]
dic[key.stringValue] = value
counter += 1
}
return dic
}
}

extension Array where Element == MyStruct {
func jsonArray() -> [[String: Any]] {
var array = [[String:Any]]()
for element in self {
array.append(element.jsonDictionary)
}
return array
}
}

You can do this without the CodingKeys (if the table attribute names on server side are equal to your struct property names). In that case just use the ‘name’ from mirror.children.

If you need CodingKeys don’t forget to add the CaseIterable protocol. That makes it possible to use the allCases variable.

Be careful with nested structs: E.g. if you have a property with a custom struct as type, you need to convert that to a dictionary too. You can do this in the for loop.

The Array extension is required if you want to create an array of MyStruct dictionaries.