JSON Parsing in Android

The question:

I have searched alot on JSON Parsing in Android, but couldn’t quite convinced. Actually got a brief idea but not so clear yet regarding JSON Parsing.

How to implement the JSON Parsing in the Application?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

This is a very simple JSON String


In order to get values for it use JSONObject like this :

JSONObject json_obj=new JSONObject(your json string);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");

This is a slightly complex json string


In order to extract values from this use JSONArray

JSONArray jArray=new JSONArray(your json string);
for(int i=0;i<(jArray.length());i++)
    JSONObject json_obj=jArray.getJSONObject(i);
    String value1=json_obj.getString("key1");
    String value2=json_obj.getString("key2");

Hope this helps a bit………..

Method 2

You can also check out Google’s GSON library here. The GSON user guide here has some useful examples to help get you started. I’ve found GSON to be simple and powerful.

Method 3

See: http://developer.android.com/reference/org/json/package-summary.html

Primarily, you’ll be working with JSONArray and JSONObject.

Simple example:

    try {
        JSONObject json = new JSONObject(jsonString);
        int someInt = json.getInt("someInt");
        String someString = json.getString("someString");
    } catch (JSONException e) {
        Log.d(TAG, "Failed to load from JSON: " + e.getMessage());

Method 4

You can use the org.json package, bundled in the SDK.

See here: http://developer.android.com/reference/org/json/JSONTokener.html

Method 5

One more choice: use Jackson.

Simple usage; if you have a POJO to bind to:

  ObjectMapper mapper = new ObjectMapper(); // reusable
  MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream
  // back to JSON:
  String jsonString = mapper.writeValue(value);

to a Map:

  Map<?,?> map = mapper.readValue(source, Map.class);

or to a Tree: (similar to what default Android org.json package provides)

  JsonNode treeRoot = mapper.readTree(source);

and more examples can be found at http://wiki.fasterxml.com/JacksonInFiveMinutes.

Benefits compared to other packages is that it is lightning fast; very flexible and versatile (POJOs, maps/lists, json trees, even streaming parser), and is actively developed.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment