Ios – Serializing complex NSObject to JSON pattern

iosjsonjsonkit

I have a series of NSObject's I would like to serialize to JSON and post to a service. The final object consists of several levels of these NSObject subclasses nested within each other.

Each one of these objects follows a protocol with a method which returns that objects properties in an NSDictionary with the appropriate keys. However, some of these properties are other objects and so forth, making the serialization a bit complicated.

Is there a pattern I could use to simplify serializing the final object? Using JSONKit, it seems I would need to serialize each dictionary individually from the deepest object and work backwards, checking for errors, then adding to a compound string. I know this can not possibly be the best method using this very capable library. Any suggestion or guidance is welcomed.

Edit 1

JSONKit GitHub URL

JSONKit Readme Documentation

Best Answer

The AutomagicCoding library uses low-level property introspection to recursively convert any NSObject into an NSDictionary, which can then be directly serialised as JSON:

https://github.com/psineur/NSObject-AutomagicCoding

It may involve a bit of fine-tuning for classes with properties that are structs, etc, but it's probably the easiest, least labour-intensive approach you'll find.

UPDATE:

I've since written my own library, HRCoding (https://github.com/nicklockwood/HRCoder) that can load/save any object as JSON using the NSCoding protocol)