Journeyman Journeyman - 1 month ago 13
iOS Question

JSON serialisation of NSOrderedSet within iOS

What are my options for serialising and deserializing NSOrderedSets to JSON? I'm using iOS5 / Objective-C. I guess I could roll my own, but I'm assuming there are some good existing frameworks out there...

Answer

Your only option is probably, to get access on an OpenSource library and take a look at the code how the JSON Serializer is implemented. Then you could possibly extend the library for your purpose. By "extending" I mean, that you should utilize as much as possible from the existing library, since making your own serializer from scratch can be a lot of work.

Usually, the JSON libraries define a mapping between the JSON types and the corresponding Objective-C types (classes). For instance, a JSON Array maps to a NSArray/NSMutableArray, a JSON Object maps to a NSDictionary/NSMutableDictionary, etc.

The "JSON Serializer" would therefore "know" how to serialize a "mapped" Objective-C object into a JSON element. One way to implement this behavior is to add a Category to the mapped Objective-C class.

So, when "extending the library" (depending on the library and the implementation), it may be sufficient to just add a Category for your custom classes and implement it accordingly.

I'm an author of a JSON library. Creating Categories for custom classes which then can be used in the JSON Serializer wouldn't be that much effort. You might specify your needs in an Enhancement request, so I could possibly adjust the library to make it more easy to add Custom classes.

Your Category would look like as follows:

@interface NSOrderedSet (JPJsonWriter) <JPJsonWriterInserterProtocol>
@end

@implementation NSOrderedSet (JPJsonWriter)

- (int) JPJsonWriter_insertIntoBuffer:(NSMutableDataPushbackBuffer*)buffer 
                             encoding:(JPUnicodeEncoding)encoding
                              options:(JPJsonWriterOptions)options
                                level:(NSUInteger)level
{
    return insertJsonArray(self, buffer, encoding, options, level);
}

@end

This is actually all what you have to do - after making a few adjustments to my library. But please note: this is dependent on the JSON library you are using. You can find my JSON library on here. Please file an enhancement request - thank you.