In iOS 5, Apple introduced NSJSONSerialization, for parsing JSON strings.

But, as on date, you might have already developed your app using a third party component like JSONKit or json-framework or TouchJSON and you might not want to migrate your complete code base to NSJSONSerialization. In fact removing or replacing an existing framework is not really an easy thing especially if you have a lot of dependencies. However, moving towards Apple’s implementation is always safer to use since you have the guarantee that it will be maintained kept up to date.

The Adapter Design Pattern

This is where the Adapter design pattern comes to rescue.
Adapters are classes that helps in migrating your code base with as low side-effects as possible. If you were depending on the class categories in your third party framework, which is probably the case, you can use my “adapter” classes to route those messages to Apple’s framework. That way, all you need to do is to copy couple of files from my framework, and ditch your third party json parsing frameworks. It should all start working automatically.


Let’s see how that works.

The adapter classes I wrote “adapts” your code to use Apple’s NSJSONSerialization instead of your third party framework. Did I say that the whole adapter classes run under a hundred lines of code?
For example, if you call JSONValue of json-framework in your code like this,


NSString *jsonString = [NSString stringWithContentsOfURL:@http://example.com/test.json"];
[jsonString JSONValue];

my adapter routes the “JSONValue” extension method to Apple’s implementation. The adapter classes have similar implementations for every similar category method in the framework.

Source Code

The source code is pretty elementary right now and supports only json-framework. and I’m maintaining them on Github here.

https://github.com/MugunthKumar/third-party-json-adapters

Expecting volunteers to write equivalent adapters for other frameworks (especially for frameworks that are slower than Apple’s)

Mugunth

Follow me on Twitter