7

There are a number of questions and answers on SO that ask how do I serialise an object to in objective c.

The following 3 methods are all mentioned in the above links.

1) Use NSJSONSerialization to serialise the object to JSON. Seems good but this requires the object in question to be either an array or dictionary at its top level. Common solution is to declare custom toDictionary or serialise method that loops over the properties and sets the relevant key and values.

2) Conform to the NSCoder protocol, a little like the approach above but there seems to be some confusion around whether or not this can serialise to JSON or just to NSData.

3) Third party library.

I'm getting slightly confused as to what approach to take. I want to serialise to JSON, there are contradictory answers some stating you can use NSCoder some saying not. I know that a third party app will work however I'd rather implement something simple like options 1 or 2.

Thoughts?

Community
  • 1
  • 1
teddy777
  • 661
  • 8
  • 20
  • I'm writing a port of Backbone.js to Objective C. You could have a look at how I handled JSON (de)serialization: https://github.com/geon/Backbone.m/blob/master/BackboneModel.m#L229 – geon Sep 21 '15 at 06:49

1 Answers1

0

With 1, you'd basically be writing a JSON-based implementation of NSCoder from scratch. Certainly doable, though.

With 2, I believe it might be possible, since I think the output of NSCoder is some variant of XML (though compressed into a binary blob). However, I don't know if this is a great approach, since the format is proprietary and not really meant to be human-editable. There might also be a mismatch between what's allowed in JSON vs. the NSCoder format in terms of keys and leaf nodes, forcing you to do a messy conversion.

I've been trying to do something similar, and based on my research, I actually suggest 3. Using something like Mantle — a stable, polished framework that gets frequent updates — you can specify exactly how your model objects will be serialized to and deserialized from JSON. It even supports the NSCoder protocol as an option! (This is effectively solution 1, but vetted and maintained by a 3rd party.)

Archagon
  • 2,470
  • 2
  • 25
  • 38