4

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.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

5

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
}
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • If we get the data out again, is it a new object, with no reference to the one serialized whatsoever? Thanks. – Unheilig Dec 01 '14 at 15:03
  • 1
    And what if I have one more property in the `Foo` structure? What should I write in the `map` argument then? – FrozenHeart Dec 01 '14 at 15:04
  • @Unheilig dataWithJSONObject return data as UTF8 JSON string bytes. So of course you need to create new object to deserialize it. – Kirsteins Dec 01 '14 at 15:08
  • 1
    @FrozenHeart You need to map it to dictionary then. `self.arr.map{ ["bar" : $0.bar, "someOtherValue" : $0.someOtherValue] }` – Kirsteins Dec 01 '14 at 15:11