在Swift中用数组序列化自己的对象的更优雅的方法是什么 [英] What is the more elegant way to serialize my own objects with arrays in Swift
本文介绍了在Swift中用数组序列化自己的对象的更优雅的方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的课:
I have a classes that looks like this:
class Foo {
var bar = Int()
}
class Bar {
var baz = String()
var arr = [Foo]()
}
并且我有一个Bar结构的对象,需要将其序列化为JSON:
and I have an object of Bar structure that I need to serialize to JSON:
let instance = Bar()
通过标准库或某些第三方库执行此操作的更优雅的方法是什么?
What is the more elegant way to do it via standard library or some third-party libraries?
谢谢.
推荐答案
我建议采用这种方法:
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
}
这篇关于在Swift中用数组序列化自己的对象的更优雅的方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文