Going native with JSON: iOS, Android and Windows 8


There are essentially two different ways in which JSON can be handled when programming. The first is to parse the JSON objects into native Objective-C, Java, or C# objects within the respective operating systems and the second is to manipulate the JSON within a confined set of methods exclusive to the handling of JSON (or at least rely on these methods for the passing on of information and processing of objects).

Advantages and disadvantages

The advantage of the former method is that it opens out the entire set of system methods to the object data, while also enabling additions to the data. This might well include the addition of native objects to an array or object as a value. The disadvantage is that the JSON is then exposed to a whole range of non-specific methods and must maintain itself in a way that makes sense if it is to be returned to a JSON format at the end of being manipulated. (e.g. if we were to add values to dictionaries and arrays that are Objective-C objects rather than strings, then it would not then be possible to transform back into JSON without further parsing.)

Transformation into native objects

The transformation into native objects is what the NSJSONSerialization Class provides in iOS. It contains only five public methods and simply transforms JSON into Objective-C and vice versa. (For usage see this earlier post.)

Separate JSON handling using its own classes

Android and Windows take a different approach. You use a JSONTokener in Android to transform a string into something that the JSON classes and their methods can work with, while the JSONStringer goes the other way and transforms the JSON object into a string.

Once a string has been tokenized it can then be manipulated using the 40 public methods of JSONArray and the 40 public methods of JSONObject.

Windows takes a similar approach to Android by using the JsonValue class to tokenize or parse a JSON string into a JSON array or object. The JSON can then be manipulated through the JsonValue class as well as through JsonObject and JsonArray.

Switching approaches

If you do not wish to follow Apple's approach of parsing into native objects, then one option is to use instead JavaScriptCore as a method of parsing JSON to separate JSON from native code. If on the other hand you wish to follow Apple's approach for Windows you should explore the Json.NET framework, and for Android you might explore Gson, Jackson, JSON Simple, etc.

Further reading:

jsmn - a JSON parser written in C (good explanation of what a token is).

Json.NET - a framework for use with .NET

Using JavaScript Object Notation (JSON) (Windows Dev Center)

How To Convert Java Object To / From JSON (Jackson)

How do I parse JSON from a Java HTTPResponse? (StackOverflow)

JsonReader and JsonWriter (Android Developers)


Endorse on Coderwall

Comments