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

1.8k Views Asked by At

I have a classes that looks like this:

class Foo {
    var bar = Int()
}

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

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?

Thanks in advance.

1

There are 1 best solutions below

4
On BEST ANSWER

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
}