avatar

Swift-利用Mirror创建结构体字典(JSON)
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.

文章作者: X Mεl0n
文章链接: http://www.zrzz.site/2020/07/14/Swift-%E5%88%A9%E7%94%A8Mirror%E5%88%9B%E5%BB%BA%E7%BB%93%E6%9E%84%E4%BD%93%E5%AD%97%E5%85%B8%EF%BC%88JSON%EF%BC%89/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记

评论