Simple Android JSON Parser Example Code with URL and Logcat Output


android json parser example

Today I’m going to share an Android JSON Parser example code to parse a JSON string from a URL.

This code is really useful because nowadays, JSON string is being used by most APIs like Facebook graph API and Google Maps.

You should use JSON in your projects instead of XML because it is lightweight, so much easier to parse, and is supported by most programming language.

Recently, I wrote about how to generate JSON string with PHP which can be useful for you too.

But if you really have to use XML, you can also take a look at my older post: Parse XML in Android With Three Input Sources

DOWNLOAD SOURCE CODE

We will cover the following contents in this post:

1.0 Creating JSON String
2.0 Creating our JSON Parser Class
3.0 Using JSON Parser Class with JSON String
4.0 Logcat Output
5.0 Online Resources

1.0 Creating JSON String

Create a JSON string and make it accessible via URL. I created an example for this post, you can see it in this URL: http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php

What it looks like in a JSON viewer:

android-json-parser-example-json-string

As for the code on how to create that JSON string, you can take a look at my older post: Generating JSON String with PHP

2.0 Create our JSON Parser Class

You can use this JSON parser class with any of your JSON string from URL. Here’s our JsonParser.java:

package com.example.androidjsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonParser {

    final String TAG = "JsonParser.java";

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String url) {

        // make HTTP request
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            Log.e(TAG, "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

3.0 Using JSON Parser Class with JSON String

Now we want to make use of our JSON parser with the generated JSON string from URL. But before running our code, make sure you enable internet permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Now take a look at our MainActivity.java:

package com.example.androidjsonparsing;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // we will using AsyncTask during parsing 
        new AsyncTaskParseJson().execute();
    }

    // you can make this class as another java file so it will be separated from your main activity.
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                dataJsonArr = json.getJSONArray("Users");

                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String firstname = c.getString("firstname");
                    String lastname = c.getString("lastname");
                    String username = c.getString("username");

                    // show the values in our logcat
                    Log.e(TAG, "firstname: " + firstname 
                            + ", lastname: " + lastname
                            + ", username: " + username);

                }

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

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {}
    }
}

4.0 Android JSON Parser Example Logcat Output

It is important for us to see the extracted data from the JSON string or URL. So here’s the logcat output of our code for today.

android-json-parsing-tutoril

5.0 Online Resources

I think the following online resources can also help you in doing such tasks. Check them out!

How to parse JSON in Android?
Android JSON Reader

If you have any other solutions or comments to improve this Android JSON parser example code, please let us know in the comments section below. Thanks for reading our code tutorial!


23 responses to “Simple Android JSON Parser Example Code with URL and Logcat Output”

  1. Hey Mike, I’ve started with Android a few months ago, so please, correct me if I’m wrong, in the AsyncTask there, I think that the right way of doing it, would be to loop trough the results in the “OnPostExecute” method as the Android Developers says in the “Four Steps” of the AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
    Sorry if I’m wrong, but im using a code like that in an app I’ve made, and I’d like to correct it if it’s wrong.
    Thank you very much.
    Leonardo, Argentina.

    • Hi @leonardochaia:disqus, thanks for sharing your thoughts! You should loop inside OnPostExecute if you already have the values stored in an array variable AND inflating or working with the views.

      In our example code above, I’m looping inside doInBackground() because I’m not working with the views and I just want to print the values it gets from the JSON string.

  2. can we fetch multiple urls to parse multiple json in different activities ?
    i don’t how to give multiple urls in mail activity and fetch them in different activities

    thank you

  3. You should change code this ” sb.append(line + “n”); ” to => ”
    sb.append(line + “n”);”

  4. I don’t get the parse part. if I have already set the array in the .php file, how do I call it in the java class?

Leave a Reply

Your email address will not be published. Required fields are marked *