Android

Undertanding and Working With JSON in Android

android parsing json data
Written by Yasir Ameen

JSON (JavaScript Object Notation) is very powerful when transmitting information between Server to Client. It is not  necessary that information or data is always sent by Server to Client but it can also be Client to Server or Vice-Versa. Server and Client talk through some medium which is called HTTP (Hyper Text Type Protocol). Server and Client interchange different types of information such as Text, Image,Video , Audio or etc. In term of HTTP we refer these information as MIME Type which means what kind of information Server and Client dealing. In this article we will see how to deal with JSON information.

 Let’s Start Working With JSON in Android

WHAT IS JSON?

We use JSON to communicate between Server and Client. Server send information to client  in JSON format then client parse this information to use it. Similarly Client sends information to Server then Server parse this information in order to use it.

Following is sample JSON of facebook posts, just to give you an idea how json look like.

   {
  "data": [
    {
      "id": "123456789",
      "from": {
        "name": "Yasir Ameen", "id": "AF2"
      },
      "message": "Looking forward to 2017!",
      "actions": [
        {
          "name": "Comment",
          "link": "http://www.facebook.com/X111/posts/C5555"
        },
        {
          "name": "Like",
          "link": "http://www.facebook.com/X111/posts/C5555"
        }
      ],
      "type": "status",
      "created_time": "2017-08-02T21:27:44+0000",
      "updated_time": "2017-08-02T21:27:44+0000"
    },
    {
      "id": "X998_Y998",
      "from": {
        "name": "Peyton Manning", "id": "X18"
      },
      "message": "Where's my contract?",
      "actions": [
        {
          "name": "Comment",
          "link": "http://www.facebook.com/X998/posts/Y998"
        },
        {
          "name": "Like",
          "link": "http://www.facebook.com/X998/posts/Y998"
        }
      ],
      "type": "status",
      "created_time": "2015-08-02T21:27:44+0000",
      "updated_time": "2015-08-02T21:27:44+0000"
    }
  ]
}

 

TERMS USED IN JSON?

1) Key-Value Pairs

JSON information consist of key-Value pairs, value can be any primitive types.

"name": "Yasir Ameen",
"email": "YasirAmeen@Gmail.com",
"phone": "123456789"

 

2) JSON Object

JSON Object is represented by curly braces { } and it may contains numbers of key-value pairs.

 {
  "name": "Yasir Ameen",
  "email": "YasirAmeen@Gmail.com",
  "phone": "0123456789"
}

 

3) JSON Array

JSON Array is represented by Square brackets [ ].


{
  "name": "Yasir Ameen",
  "email": "YasirAmeen@Gmail.com",
  "phone": 123456,
  "posts": [
    "http://yasirameen.com/2016/11/testing-androd-apps/",
    "http://yasirameen.com/2016/09/android-realm-mobile-database/",
    "http://yasirameen.com/2016/10/android-creating-app-walkthroug/"
  ]
}

 

See the following image and see how JSON information is read. Left side is json formatted data and right side is also an JSON data with terms used to understand json data .

json data android

WRITING JSON FROM CLIENT SIDE

When i was beginner, i was in need how to create json using java or android and i found it very cool by creating JSON using native java code. Lets see how you can create JSON data. We will look following

  1. Creating Simple JSON Object
  2. Creating JsonArray Inside JSON Object
  3. Creating Combination of JSON Object and JsonArray

 

Creating Simple JSON Object

Following code snippet will create simple JSON object using code.

  try {
    JSONObject object = new JSONObject("details");

    object.put("firstName","Yasir");
    object.put("lastName","Ameen");
    object.put("Phone","+923331234567");
    object.put("Country","Pakistan");
    object.put("postalCode",75850); //Value is int

    //if you want to modify some value just do like this.
    object.put("postalCode",88888);
    Log.d("json",object.toString());

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

//The Out of the above code is here.
/*{
       "firstName": "Yasir",
        "lastName": "Ameen",
        "Phone": "+923331234567",
        "Country": "Pakistan",
        "postalCode": 75850
}*/

 

JSON Object Inside JSON Object

It is very easy to put JSON object inside JSON object, idea is similar as above but you create another JSONObject instance.

   try {
     JSONObject object = new JSONObject();

     object.put("firstName","Yasir");
     object.put("lastName","Ameen");
     object.put("Phone","+923331234567");
     object.put("Country","Pakistan");
     object.put("postalCode",75850); //Value is int

     //if you want to modify some value just do like this.
     object.put("postalCode",88888);

     JSONObject details = new JSONObject();
     details.put("details",object);
     Log.d("json",details.toString());

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

 //The Out of the above code is here.
/* {
     "details": {
             "firstName": "Yasir",
             "lastName": "Ameen",
             "Phone": "+923331234567",
             "Country": "Pakistan",
             "postalCode": 88888
       }
     }
 */

Creating JsonArray Inside JSON Object

Similarly it is very easy. Just create Instance of JsonArray and set arrays values using the Put() method.

   try {
     JSONObject object = new JSONObject();

     object.put("firstName","Yasir");
     object.put("lastName","Ameen");
     object.put("Phone","+923331234567");
     object.put("Country","Pakistan");
     object.put("postalCode",75850);

     JSONArray posts = new JSONArray();
     posts.put("http://yasirameen.com/2016/11/handling-app-crashing/");
     posts.put("http://yasirameen.com/2016/10/android-creating-app-walkthrough/");
     posts.put("http://yasirameen.com/2016/10/android-material-sign-in/");
     posts.put("http://yasirameen.com/2016/11/testing-androd-apps/");


     object.put("Posts",posts);

     Log.d("json",object.toString());

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

 //The Out of the above code is here.
/* {
       "firstName": "Yasir",
       "lastName": "Ameen",
       "Phone": "+923331234567",
       "Country": "Pakistan",
       "postalCode": 75850,
       "Posts": [
         "http://yasirameen.com/2016/11/handling-app-crashing/",
         "http://yasirameen.com/2016/10/android-creating-app-walkthrough/",
         "http://yasirameen.com/2016/10/android-material-sign-in/",
         "http://yasirameen.com/2016/11/testing-androd-apps/"
       ]
     }
 */ 

Creating Combination of JSON Object and JsonArray

Here i will show you how can combine and JSON Object along with JsonArray to create JSON.

 

PARSING JSON DATA IN ANDROID

There are several ways of parsing JSON data but you should select which one you want to choose according your choice. Let’s say you want parse just simple JsonObject or simple JsonArray, see the example below.

Parsing Simple JSON


//Parsing Simple JSON.

        {
            "Name": "Yasir",
            "Email": "YasirAmeen92@Gmail.com",
            "Website": "www.yasirameen.com",
            "Contact": {
                "mobile": "+923331234567",
                "office": "012345678"
           }
        }

try {
    JSONObject object = new JSONObject(YourJson);
    String name = object.getString("Name");
    String email = object.getString("Email");
    String website = object.getString("Website");

    //Referencing nested json objects which is "Contact
    JSONObject contact = object.getJSONObject("Contact");
    String mobile = contact.getString("mobile");
    String office = contact.getString("office");


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

Parsing Simple JsonObject and nested JsonArray

 


//Parsing nested JsonArray..

{
        "firstName": "Yasir",
        "lastName": "Ameen",
        "Phone": "+923331234567",
        "Country": "Pakistan",
        "postalCode": 75850,
        "Posts": [
            "http://yasirameen.com/2016/11/handling-app-crashing/",
            "http://yasirameen.com/2016/10/android-creating-app-walkthrough/",
            "http://yasirameen.com/2016/10/android-material-sign-in/",
            "http://yasirameen.com/2016/11/testing-androd-apps/"
    ]
}


try {
    JSONObject object = new JSONObject(YourJsonObjectOrJsonString);
    String fname = object.getString("firstName");
    String lname = object.getString("lastName");
    int pcode = object.getInt("postalCode");

    // You will get json array using index
    JSONArray posts = object.getJSONArray("Posts");
    String postOne = posts.getString(0);
    String postTwo = posts.getString(1);
    
} catch (JSONException e) {
    e.printStackTrace();
}

 

Parsing JSON Using GSON Library

As i said there are number of tutorials you can find on internet about JSON Parsing, but here i will give you an very easy way to Parse JSON. We will use GSON Library in order to Parse JSON information.

Add GSON dependencies in your project build.

compile 'com.google.code.gson:gson:2.8.0'

We are going to parse following jsonArray data which is consist of country code, dial code and name.
http://ec2-35-161-255-204.us-west-2.compute.amazonaws.com/countries.json

 

  
 [
    {
           "name":"Afghanistan",
            "dial_code":"+93",
            "code":"AF"
    },
    {
           "name":"Aland Islands",
            "dial_code":"+358",
            "code":"AX"
    },
    {
           "name":"Albania",
            "dial_code":"+355",
            "code":"AL"
    },
    {
           "name":"Algeria",
            "dial_code":"+213",
            "code":"DZ"
    }
    .
    .
    .
    .
    .

 

Creating Pojo Class For Parsing Country Information

This is the very best approach when you parse JSON data using POJO class you should always use this approach when you are going to parse JSON data in proper way.


public class Country {

 //We use GSON annotation for the field name which we want to parse.
    
    @SerializedName("name")
    private String name;
    @SerializedName("dial_code")
    private String dial_code;
    @SerializedName("code")
    private String code;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDial_code() {
        return dial_code;
    }

    public void setDial_code(String dial_code) {
        this.dial_code = dial_code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

Now create a class name call GsonUtils and paste the following code.


public class GsonUtils {

    public static <T> JSONObject toJSON(T obj)throws JSONException {
        Gson gson = new Gson();
        return new JSONObject(gson.toJson(obj));
    }

    public static <T> T fromJSON(String json,Class<T> classOfT){
        Gson gson = new Gson();
        return gson.fromJson(json,classOfT);
    }

    public static <T> T fromJSON(JSONObject json,Class<T> classOfT){
        Gson gson = new Gson();
        return gson.fromJson(json.toString(),classOfT);
    }
}

In Your MainActivity you can parse JSON array like this.


public class MainActivity extends AppCompatActivity {

    private List<Country> countryList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        countryList = new ArrayList<>();
        try {
        JSONArray countries = new JSONArray(YourJSONArrayString);
        for (int i = 0; i < countries.length(); i++) {
            JSONObject object = countries.getJSONObject(i);
            countryList.add(GsonUtils.fromJSON(object,Country.class));
            //Thats all 🙂
            // Now you can use this countryList ArrayList.
        }

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

 

 

 

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

Leave a Comment