What is the more elegant way to serialize my own objects with arrays in Swift

蹲街弑〆低调 提交于 2019-12-05 12:46:34

I suggest taking this approach:

class Foo {
    var bar = Int()
}

class Bar {
    var baz = String()
    var arr = [Foo]()

    var jsonDictionary: NSDictionary {
        return [
            "baz" : self.baz,
            "arr" : self.arr.map{ $0.bar }
        ]
    }
}

let bar = Bar()
bar.baz = "some baz"
bar.arr.append(Foo())

var error: NSError?
let data = NSJSONSerialization.dataWithJSONObject(bar.jsonDictionary, options: nil, error: &error)

if error == nil && data != nil {
    // success
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!