Android Core

Android JSON Tutorial: Create and Parse JSON data

This tutorial describes how to use JSON with AndroidJSON 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.

Introduction to JSON

JSON uses 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. Array can be used to model list, array of objects and so on. So using these two structure 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:

public class Person {

    private String name;
    private String surname;    
       .....
}

it can be represented in JSON in this way

{"surname":"Swa",
 "name":"Android",
  ....
}

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 type of operation:

  • 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 first step, convert java class to JSON data. As example, let’s suppose we have a class Person like this:

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      
    }
}

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 an utility class.

public class JsonUtil {

public static String toJSon(Person person) {
      try {
        // Here we convert Java Object to JSON 
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", person.getName()); // Set the first name/pair 
        jsonObj.put("surname", person.getSurname());

        JSONObject jsonAdd = new JSONObject(); // we need another object to store the address
        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;

}

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 reperesent 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 an 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:

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

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

android_json_tutorial[4]


 

Parse JSON Data: Deserialization

Another interesting aspect is parsing JSON data 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 instantiate a parser that helps to get the values inside JSON.

JSONObject jObj = new JSONObject(data);

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:

String surname = jObj.getString("surname");

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

JSONObject subObj = jObj.getJSONObject("address");
String city = subObj.getString("city");
...

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

JSONArray jArr = jObj.getJSONArray("list");
for (int i=0; i < jArr.length(); i++) {
    JSONObject obj = jArr.getJSONObject(i);
    ....
}

Using these pieces of code we can handle JSON in Android. If you are interested on 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.

Source code available @ github
 

Francesco Azzola

He's a senior software engineer with more than 15 yrs old experience in JEE architecture. He's SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. He is an android enthusiast and he has worked for long time in the mobile development field.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

24 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
falah
falah
10 years ago

Hi, Its a great tutorial , thank you
i have downloaded full source code, but its result is in json only..? why its not converting..??

Rahul
Rahul
10 years ago

Thanks a lot. This is the best tutorial of JSON. :)

wasim memon
10 years ago

nice tutorial .
but how i can store json data local and use them from my app at run time ?

Andrea
Andrea
10 years ago

Gracias!, este es un gran aporte…… Dios te bendiga!

Amri
Amri
10 years ago

Hi ! Its awesome, ive been googling for this tutorial, and i had visited many website, but they dont give me a clear explanation like this, thank you so much for this tutorial :D

kanibalv
kanibalv
10 years ago

I belive there is a problem on:

JSONArray jArr = jObj.getJSONArray(“list”);

should be
JSONArray jArr = jObj.getJSONArray(“phoneNumber”);

I am right?

harish
harish
9 years ago

2{“Product”:[{“id”:”2″,”name”:”Nokia”},{“id”:”3″,”name”:”Samsung”}],”success”:1}

harry
harry
9 years ago

2{“Product”:[{“id”:”2″,”name”:”Nokia”},{“id”:”3″,”name”:”Samsung”}],”success”:1}

how code is parse it start from 2

Yawar
Yawar
9 years ago

Very easy to understand. (Y)

Murugeswari
Murugeswari
9 years ago
Reply to  Yawar

can you tell ..? hoe to store data in local database

RAKSHIT
RAKSHIT
9 years ago

Nice work

Murugeswari
Murugeswari
9 years ago
Reply to  RAKSHIT

i tried above code but not working show some error

Murugeswari
Murugeswari
9 years ago
Reply to  Murugeswari

please guide me …what i want to change this code

swat
swat
9 years ago

but how to Parse JSON from 2 Array like :
{“Product”:[{“id”:”2″,”name”:”Nokia”},{“id”:”3″,”name”:”Samsung”} ] } {“Year”:[{“id”:”2″,”name”:”2013″},{“id”:”3″,”name”:”2014″} ] }

gunjot singh
gunjot singh
9 years ago

It is a superb tutorial, didn’t found any clean post like this on whole web. Thanks

shakti
shakti
9 years ago

Your code is good
Can you tell me how to get data from URL

Murugeswari
Murugeswari
9 years ago

sir

i tried above code ..but i faced one error ,mention the getName and getAddres in person class etc for all get methods ..please guide me

I have another doubt.how store the data in local data base

please guide me

andrea
andrea
8 years ago

can I send the Json Object to webview?

verstian
verstian
8 years ago

Nicely written by Mr. Francesco Azzola if any developer is looking to parse json data using andriod studio he can follow this tutorial;
http://mobilesiri.com/json-parsing-in-android-using-android-studio/

Carl
7 years ago

Well the example is very good – but what if I just have a JSON array without a object name like [{catname = fruits},{catname = cookies}]. How do I parse that? It don’t have a object name in the JSON string, so I’m a bit stuck :(

Bapi
Bapi
6 years ago

need help for Java POJO Class to generate the JSON like below example. Runtime date array

{“result”:
[
{“2017-04-17”:[{“Name”:”Sanu”,”Gender”:”M”},{“Name”:”Lili”,”Gender”:”F”},{“Name”:”Sunil”,”Gender”:”M”}]},
{“2017-04-18”:[{“Name”:”Sumi”,”Gender”:”F”},{“Name”:”Richa”,”Gender”:”F”}]}
],
“subject”:”pass”
}

vishwas
vishwas
5 years ago

{
“result”: [
{
“product_id”: “1”,
“stockiest_id”: [
“13”,
“5”
],
“product_name”: “coolpad note 3 lite”,
“product_description”: “lorem ipsome lorem ipsome lorem ipsome lorem ipsome lorem ipsome lorem ipsome lorem ipsome lorem ipsome lorem ipsome “,
“product_price”: [
“7001.00”,
“91.00”
],
“product_image”: “coolpad_note_3_lite__Lava-Z60-16GB-SDL274620647-1-bdfb312.jpg”,
“let”: [
“22.962267199999996”,
“22.753285”
],
“long”: [
“76.0507949”,
“75.893696”
],
“available_qty”: [
“30”,
“1021”
]
},

how can i parse the array below and can i get the values in another activity …
please give me a solution

21321321
21321321
4 years ago

thanks for the tutorial

Back to top button