Parse JSON data in Android

This tutorial describes how to parse JSON data in Android. JSON stands for (Java Script Object Notation). It is a simple and light-weight data interchange format that can be easily read by humans and machines. JSON is a text format that is language independent. It represents data in a text format so that can be easily parsed.
JSON is widely used nowadays and it is important to know how to use it and extract information. Almost all remote services use JSON to exchange data with a client. This tutorial explores how to parse JSON data in Android so that an Android app can call almost all remote services.

You can download the source code of this tutorial here:

 

Parse JSON in Android

Getting started with JSON in Android

In Android parse JSON object has two different of structures:

  • Collection of name/value pair
  • Array

The first structure can be used to model object because an object is a collection of attributes that hold some values. An Array can be used to model list, array of objects and so on. So using these two structures we can transfer data between two machines in a simple and efficient way. Lately, JSON is having a great success and most of the API available support JSON format. Let’s see how we can represent data in JSON.

An object in JSON is modeled using {..}, while its attributes can be modeled using name : value pair.Value can be, in turn, an object, an array or a “simple” value, like a primitive value (int, String, boolean and so on).

So if we have for example a java class like:

[java]public class Person {

private String name;
private String surname;
…..
}[/java]

it can be represented in JSON in this way

[xml] {“surname”:”Swa”,
“name”:”Android”,
….
}
[/xml]
An array is represented in JSON using [..]. An array element can be an object, an array and so on.

Now we know a bit better JSON format, we can start using JSON with Android.

Using JSON in Android

In Android, and in general in all environments, there are two types of operations:

  • Convert java class to JSON data (Serialization)
  • Parse JSON data and create java classes (Deserialization)

Let’s suppose we have to send data to a remote server using HTTP connection and the data is represented in a java class. We have, as the first step, convert java class to JSON data. As an example, let’s suppose we have a class Person like this:

[java]public class Person {
private String name;
private String surname;
private Address address;
private List<PhoneNumber> phoneList;

// get and set

public class Address {
private String address;
private String city;
private String state;
// get and set
}

public class PhoneNumber {
private String type;
private String number;

// get and set
}
}[/java]

This class, as you can see, cover almost all the object type: there’re strings, array, inner class and so on.

How to convert it to JSON?. Let’s create a utility class.

[java]public class JsonUtil {

public static String toJSon(Person person) {
try {
// Here we convert Java Object to JSON
JSONObject jsonObj = new JSONObject();
// Set the first name/pair
jsonObj.put(“name”, person.getName());
jsonObj.put(“surname”, person.getSurname());
// we need another object to store the address
JSONObject jsonAdd = new JSONObject();
jsonAdd.put(“address”, person.getAddress().getAddress());
jsonAdd.put(“city”, person.getAddress().getCity());
jsonAdd.put(“state”, person.getAddress().getState());

// We add the object to the main object
jsonObj.put(“address”, jsonAdd);

// and finally we add the phone number
// In this case we need a json array to hold the java list
JSONArray jsonArr = new JSONArray();

for (PhoneNumber pn : person.getPhoneList() ) {
JSONObject pnObj = new JSONObject();
pnObj.put(“num”, pn.getNumber());
pnObj.put(“type”, pn.getType());
jsonArr.put(pnObj);
}

jsonObj.put(“phoneNumber”, jsonArr);

return jsonObj.toString();

}
catch(JSONException ex) {
ex.printStackTrace();
}

return null;

}[/java]

Let’s analyze the code. At line 6, we create a new JSON Object, it acts a container of our data. Next, we put some name/value pair (line 7-8). As you can see they match the attribute of Person class. Looking at line 10 of Person class, we note we have an inner class, so we need another JSON object to represent it (line 10-13). When we have built our JSON object we put it in the main object line 16. At line 17, there is a phone List in our Person class. In this case, we need a JSONArray to model the Java List and for each item, in the list, we need JSON Object to map it. Running the source code available at the end of this post, we will have:

[xml]{
“phoneNumber”: [
{
“type”: “work”,
“num”: “11111”
},
{
“type”: “home”,
“num”: “2222”
}
],
“address”: {
“state”: “World”,
“address”: “infinite space, 000”,
“city”: “Android city”
},
“surname”: “Swa”,
“name”: “Android”
}[/xml]

This is our JSON representation of our Person object. I used a nice website that helps to test JSON data (http://www.jsontest.com/).  As you can see from the result our JSON data is valid.

Parse JSON Data in Android: Deserialization

Another interesting aspect is parsing JSON data in Android and create Java classes. Even if there are automatic tools that create POJO classes from JSON data, it is important to know what’s behind. When you have a JSON data the first step is instantiating a parser that helps to get the values inside JSON.

[java]JSONObject jObj = new JSONObject(data);[/java]

where data holds the JSON string. Now looking at JSON data file, we can start extracting data. For example, if we suppose that we get a JSON data like the one shown above (see JSON Person data), and we want to get the surname:

[java]String surname = jObj.getString(“surname”);[/java]

When we want to get the address object, we can use:

[java]JSONObject subObj = jObj.getJSONObject(“address”);
String city = subObj.getString(“city”);
…[/java]

If we want to get the phone number list we simply have:

[java]JSONArray jArr = jObj.getJSONArray(“list”);
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
….
}[/java]

Using these pieces of code we can parse JSON data in Android. If you are interested in more complex JSON example give a look at Android weather app: JSON, HTTP and Openweathermap. Here it is explained how to create a full app that gets the current weather conditions.

At the end of this post, you know how to parse JSON in Android. This can be very useful when you have to invoke a remote API using HTTP that returns a JSON content.

    1. Simon MacDonald October 23, 2013
    2. Du Van Huynh December 29, 2014
    3. gpm February 12, 2015
    4. gpm February 12, 2015
    5. Phil October 8, 2015
    6. Anonymous August 16, 2018
    7. deepak March 30, 2020

    Add Your Comment