Android JSON Parsing Tutorial, learn how to parse any JSON data in Android studio. In Step by Step tutorial, we will use data and parse it in Android Studio.

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

Android JSON Parsing
Android JSON Parsing

Android JSON Parsing

JSON stands for JavaScript Object Notation. It’s a well-structured data interchange format that contains two types of forms to save data:

  1. JSONObject, data stored in curly braces { string : value }
  2. JSONArray, data stored in square brackets [ value ]

A JSONObject is an unordered set of name/value pairs. A JSONObject begins with { left brace and ends with } right brace. Each name is followed by : colon and the name/value pairs are separated by , comma.

While a JSONArray is an ordered collection of values. An array begins with [ left bracket and ends with ] right bracket. Values are separated by , comma.

Value in a JSON can be a string in “double quotes”, or any primitive data type example, a number, or true or false Boolean or null, or an object or an array. These structures can be nested.

Understanding JSON Data Structure

[
 {
   "name": "Afghanistan",
   "alpha": "AFG"
 },
 {
   "name": "Åland Islands",
   "alpha": "ALA"
 },
 {
   "name": "American Samoa",
   "alpha": "ASM"
 },
 {
   "name": "Russian Federation",
   "alpha": "RUS"
 },
 {
   "name": "United Kingdom of Great Britain and Northern Ireland",
   "alpha": "GBR"
 },
 {
   "name": "United States of America",
   "alpha": "USA"
 }
] 

In the JSON data you can view above, one can easily interpret that its a data about countries and their abbreviations.

To undestanf JSON, look at the first letter in sata structure, The ‘[ ]’ square bracket denotes that the data is wrapped in JSONArray and inside it the ‘{ }’, the curly brackets denote that each array item is a JSONObject.

Inside the JSONObject the name and alpha are keys and Country name and their alpha values are String values.

Now lets do a step by step tutorial in Android Studio for better understanding.

Android JSON Parsing Tutorial

In this Step by step tutorial on Android JSON Parsing, we will use Google Adsense API and fetch some dummy Adsense earnings for a dummy account.

Getting Started

Create an empty project in Android Studio and call Google Adsense data using Adsense API, to know more about calling API Data, see here.

This is the data we received about recent payments using the Adsense API:

{
 "kind": "payments",
 "items": [
  {
   "kind": "july#payment",
   "id": "unpaid",
   "paymentAmount": 12176.88,
   "paymentAmountCurrencyCode": "USD"
  },
  {
   "kind": "june#payment",
   "id": "2017-08-21",
   "paymentDate": "2019-06-21",
   "paymentAmount": 9301.34,
   "paymentAmountCurrencyCode": "USD"
  }
 ]
}

Getting a close look above, you can see that the data is wrapped in JSONObject { } and it has two keys, “kind” which has a string data and “items” which has a JSONArray.

Once the data is received using the AsyncTask, We will parse the JSON data. We will fetch the payStatus, payAmt, payCurr from the JSONArray ‘items’, using the following lines of code:

JSONArray jsonArray = null;
try {
    jsonObject = new JSONObject(paymentsJSON);
    JSONArray jsonArray = jsonObject.getJSONArray("items");
    for(int i = 0; i < jsonArray.length(); i++ ){
        JSONObject items = jsonArray.getJSONObject(i);
        String payStatus = items.getString("id");
        int payAmt = items.getInt("paymentAmount");
        String payCurr = items.getString("paymentAmountCurrencyCode");
       }

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

As you can see in the first line we have first set the paymentJSON data, JSONObject as jsonObject and then in it searched for key ‘item’.

The value of the item is a JSONArray and using for loop in Java iterated the whole item arrays. The items.getString(“id”) finds the String with key name, ‘id’ and finds the value String and sets it equal to the variable payStatus.

Similarly, the items.getInt(“paymentAmount”) finds the key name, ‘paymentAmount’ and finds the value int and sets it equal to the variable payAmt.

Note here that JSON can have any of the following variable types:

  • a string.
  • a number.
  • an object (JSON Object)
  • an array. (JSON Array)
  • a boolean.
  • null.

Here is complete code for AsyncTask:

public static class JSONDataAsync extends AsyncTask<String,Void,String>{


    @Override    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override    protected String doInBackground(String... strings) {
        
        OkHttpClient httpClient = new OkHttpClient();
        Request request= new Request.Builder()
                .url("https://www.jsonparser.com/1248dsdf43fdw3dwe3sdasca3")
                .build();

        try {
            Response response=httpClient.newCall(request).execute();
            assert response.body() != null;
            //data is returned to onPostExecute over here            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override    protected void onPostExecute(String s) {
        super.onPostExecute(s);
      
        try {
            JSONObject jsonObject = new JSONObject(s);
            if(jsonObject.has("items")){
            JSONArray jsonArray = jsonObject.getJSONArray("items");
            for(int i = 0; i < jsonArray.length(); i++ ){
                
                JSONObject items = jsonArray.getJSONObject(i);
                String payStatus = items.getString("id");
                String payAmt = items.getString("paymentAmount");
                String payCurr = items.getString("paymentAmountCurrencyCode");
 

                tv.setText(payStatus + " " + payAmt + " " + payCurr);

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

    }
}

Android JSON Parsing Methods

There are few methods in Java that you can use for JSON Parsing in Android Studio. Here is a list and explaination of them:

Methods for JSON Object

  • get(String name): Pass the String key name and It returns the value of Object type if exists else it throws JSONException.
  • getBoolean(String name): Pass the String key name and It returns the value of Boolean type.
  • getDouble(String name): Pass the String key name and It returns the value of Double type.
  • getInt(String name): Pass the String key name and It returns the value of Integer type.
  • getJSONArray(String name): Pass the String key name and It returns the value of JSONArray type.
  • getJSONObject(String name): Pass the String key name and It returns the value of JSONObject type.
  • getLong(String name): Pass the String key name and It returns the value of Long type.
  • getString(String name): Pass the String key name and It returns the value of String type.
  • length(): It is used to get the number of name/value mappings in this object.
  • keys(): It returns the iterator of String names in the JSON Object.

Methods for JSON Array

  • get( int index ): Pass the int index and It returns the value of Object type if exists else it throws JSONException.
  • getBoolean( int index ): Pass the int index and It returns the value of Boolean type.
  • getDouble( int index ): Pass the int index and It returns the value of Double type.
  • getInt( int index ): Pass the int index and It returns the value of Integer type.
  • getJSONArray( int index ): Pass the int index and It returns the value of JSONArray type.
  • getJSONObject( int index ): Pass the int index and It returns the value of JSONObject type.
  • getLong( int index ): Pass the int index and It returns the value of Long type.
  • getString( int index ): Pass the int index and It returns the value of String type.
  • length(): It is used to get the number of name/value mappings in this object.

Leave a Reply

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

You May Also Like