How to Handle JSON in Java and Android

JSON: JavaScript Object Notation, a text based object description mechanism.

JSON is plain text
JSON is readable by human
JSON data can be parsed by JavaScript easily.
JSON data can be transported using AJAX
JSON can be handled easily Java as well as in Android.

For example, say I want to describe myself in JSON, how I do that? This can be described for example with the following properties.
Name, age, sex, homeaddres etc.

    "name": "John Kerry",
    "age": 47,
    "homeaddress": "Helsinki, Finland",
    "sex": "male"

For more details, point to

These are basically keys and values pair. name, age, homeaddress, sex are keys and corresponding values are John Kerry, 47, Helsinki, Finland and male. Notice that keys are as string and value can be string, number and array or other JSON object.

For full complete application please download from the bottom of this page. In the example, we do reverse geocoding (we get address from lattitude and longitude). We use the Google reverse geocoding API in our example.
Click on the URL and see that it will list a comples JSON object. We retrive status and address information from the JSON response.,-73.9...
"results" : [
"address_components" : [
"long_name" : "277",
"short_name" : "277",
"status" : "OK"

Some main code are explained. The JSON string can be seen if you type,-73.9... in the address bar of the browse (we are negelecting the security issues here).

     private void startDownLoadingJSON() {
        handler = new Handler();
        new Thread(new Runnable() {
            public void run() {
                String baseURLString = ",-73.961452&sensor=true";
                Log.d(LOG, "Request to = " + baseURLString);
                httphandler = new HttpHandler(baseURLString);

We need the Handler object to have an effect of Thread in Activity class. We create the HttpHandler object and set the current object as listener (Lister's method will be call back when we have the response.) Finally we send the request to fetch data.

After a while we get the response, HttpHandler object read the data and pass to our activity class as HttpHandler where we have the response from hemelix server. We create a JSON object with the string.

JSONObject jsonObject = new JSONObject(resp);

We can extract the status as string by the following way.

 String respstatus = jsonObject.getString("status");

If we don't have a key in the JSON string, it would have thrown an exception. For example if we try to get "phone" that does not exists, will throw an exception.

    public void notifyHTTPRspons(final HttpHandler http) { Runnable() {
            public void run() {
                //Set some default values that we show if there are problems
                String jsonUIStatus = "Error ";
                String jsonUIAddress = "Not Found ";
                if (http.getResCode() == HttpURLConnection.HTTP_OK
                        || http.getResCode() == HttpURLConnection.HTTP_ACCEPTED) {
                    String resp = http.getResponse();
                    Log.d(LOG, "resp =  " + resp);
                    try {
                        //Make a json object from the response
                        JSONObject jsonObject = new JSONObject(resp);
                        String respstatus = jsonObject.getString("status");
                        //Check if the status was OK
                        if((respstatus.compareTo("OK") == 0) || (respstatus.compareTo("ok") == 0)){
                            Log.i(LOG, "respstatus =  " + respstatus);
                            jsonUIStatus = "Status: " + respstatus;
                        //Make a JSON array from the object (that contains array)
                        JSONArray arr  = jsonObject.getJSONArray("results");
                        Log.i(LOG, "arr length =  " + arr.length());
                       for(int i=0; i &lt  arr.length();i++)
                            JSONObject json_data = arr.getJSONObject(i);
                            boolean addresskey = json_data.has("formatted_address");
                            if(addresskey == true) {
                                String address = json_data.getString("formatted_address");
                                //Want to show only first address, we may not need loop
                                if(i == 0) {
                                    jsonUIAddress = "Address: " + address;
                                Log.i(LOG, "address =  " + address);
                    } catch (NullPointerException ex) {
                        Log.i(LOG, ex.getMessage());
                    } catch (JSONException e) {
                        Log.i(LOG, e.getMessage());
                //Set the UI with the found status and address, 
                //if we had error then the default error is shown, make sure phone has network connection

Please download the example and run it emulator (you need to have already network connection to fetch data). You are free to use this code anywhere in anyway you wish.

Download JSON example source code

If you think this tutorial was helpful you could consider helping us so we can improve the site in more useful way.