我正在尝试像JSONModel这样在Swift中进行JSON数据建模。意味着无论您的模型是什么,都将由获取的JSON填充。谁能引导我朝同一方向前进?
我首先要做的是使用Mirror(reflecting:)从类中获取属性列表,但是如果模型是这样的-

public class Person {
    var name: String!
    var age: Int!
    var location: Location!
}

public class Location {
    var street: String!
    var city: String!
    var country: String!
}


然后对于Person类,我只获得属性[“ name”,“ age”,“ location”],而不是Location类的属性。如果仅在Mirror(reflected:)中传递Person实例,我也如何获取位置的属性
我是否正朝着正确的方向前进?如果我不愿意,也可以指导我。任何想法都欢迎。 (我想实现与JSONModel相同的目标)

最佳答案

您可以通过递归反射来访问所有属性。

let location = Location()
location.street = "Nt. 12"
location.city = "Chicago"
location.country = "US"

let person = Person()
person.name = "Peter"
person.age = 25
person.location = location

func traverseAllProperties(object: Any) {

    let mirror = Mirror(reflecting: object)

    if mirror.displayStyle == .class || mirror.displayStyle == .struct {
        mirror.children.forEach({ (child) in
            print(child.label ?? "")
            traverseAllProperties(object: child.value)
        })
    } else if mirror.displayStyle == .optional {
        if let value = mirror.children.first?.value {
            traverseAllProperties(object: value)
        }
    } else if mirror.displayStyle == .enum {
        mirror.children.forEach({ (child) in
            traverseAllProperties(object: child.value)
        })
    }
}

traverseAllProperties(object: person)


它打印:

name
age
location
street
city
country


我以这种方式写了HandyJSON

关于ios - Swift的JSON数据建模,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39231061/

10-12 21:05