Pages

Monday 28 May 2012

Android JSON Tutorial

JSON (Javascript Object Notation) is a lightweight, human-readable, data-interchange format. It was developed as a simpler alternative to XML, and is heavily used for web services.

Overview

There are two data structures in JSON: Objects and Arrays.

A JSON object is composed of a series of name/value pairs. The name is always a string, whereas the value can be either a string, number, boolean (true or false), null, or a nested object or array. These are written in plain text, enclosed in braces ({}); strings are enclosed in quotation marks; name/value pairs are separated by a colon; and each element is separated by a comma.

For example:

{
    "name"    : "Fred Bloggs",
    "age"        : 30,
    "car"        :
    {
        "make"    : "Ford",
        "model"    : "Capri",
        "year"    : 1978
    }
}

A JSON array consists of a list of values , separated by commas and wrapped up in a pair of square brackets ([]). There is no restriction on it to contain identical types.

For example, this is a three element array of differing types, including a nested object:

[
    33,
    true,
    {
        "name"    : "Jane Doe",
        "address"    : "1 Example Street, London, W1 1AA"
    }
]

JSONObject and JSONArray

The basic classes for processing JSON on Android are JSONObject and JSONArray. These can be found in the org.json package.

These provide constructors that can convert a properly formatted string containing a piece of JSON into a data structure allowing the values to be accessed.

JSONObject object = new JSONObject ("{\"key\":\"value\"}");
JSONArray array = new JSONArray ("[\"item 1\", \"item 2\"]");

If the string isn't correctly formatted then a JSONException will be thrown.

The fields in a JSONObject or a JSONArray can be accessed using the get or opt methods, for example getInt () or optJSONObject (). The main difference between these is that the get methods will throw a JSONException if there's no such value, whilst the opt methods return null, 0 or false if its absent.

The values in a JSONObject are identified by the key, for example:

String value = object.getString ("key");

Values can be added to a JSONObject using the put () method. This takes a key and value as its parameters.

object.put ("key", "value");

For an array, use the index to the element.

int value = array.getInt (0);

Running off the end of the array will result in a JSONException, so use the length () method to get its size.

Elements can be added to a JSONArray. The put value can be used without an index, in which case it'll be appended to the end. If an index is passed in then the element will be added there, overwriting any existing value.

array.put ("value");
array.put (0, "value");

A JSONObject or JSONArray can be converted into in String using the toString () method.

Resources

The sample code for this article can be found on GitHub at:


The Javadoc for the JSONObject and JSONArray classes can be found at:

http://developer.android.com/reference/org/json/JSONObject.html
http://developer.android.com/reference/org/json/JSONArray.html

In Android v. 3 (Honeycomb), a new set of JSON APIs was added. JsonReader extends the Reader class, and allows the contents of an InputStream to be decoded from JSON directly.

http://developer.android.com/reference/android/util/JsonReader.html

JsonWriter is the corresponding class used to write objects to an OutputStream.

http://developer.android.com/reference/android/util/JsonWriter.html

The JSON website gives a basic overview of the notation:

http://www.json.org/

There are also parsers online to check that a piece of JSON is formatted correctly. For example:

http://json.parser.online.fr