Question

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...

Was it helpful?

Solution

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.

OTHER TIPS

Since JSON doesn't have a set datatype, and its Array is ordered, you could convert to an NSArray first and then serialize, like this:

NSOrderedSet *os = [NSOrderedSet orderedSetWithObjects:@"1", @"2", @"3", nil];
NSArray *jsonArr = [os array];
// JSON Data
NSData *json = [NSJSONSerialization dataWithJSONObject:jsonArr options:0 error:nil];
// JSON String representation
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top