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
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:
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.
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”
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.
Oh ok, so I wasn’t wrong after all. Thanks you very much for answer.
You are correct if you’re using it with view widgets since it runs in the UI thread. :)
can we fetch multiple urls to parse multiple json in different activities ?
thank you
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
Hello @disqus_MV8cRizCzY:disqus, I think what you need to do is use android’s AsyncTasks, that way you can parse different URL’s at the same time in the background. See http://developer.android.com/reference/android/os/AsyncTask.html
Looking for online json viewer – analyse , use this tool. http://codebeautify.org/jsonviewer
Hey @jamesmalvi:disqus, thanks for sharing your online json viewer! I’m using this one http://jsonviewer.stack.hu/
http://codebeautify.org/jsonviewer will provide option to Minify, Beautify , Save and Share your json code..
when ever i run this code, it shows the message only “hello world” . what should i do?
You should change code this ” sb.append(line + “n”); ” to => ”
sb.append(line + “n”);”
Thanks for this tip @adiletjoldoshbekov:disqus, code above now updated!
if jsondata is changed how can i get data again?
Hello @kobeumut:disqus , It will depend on the change, but the script above uses JSON data with this format http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php
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?
Nice!
But how can you pass the parameters & set the method. whether is “POST” / “GET”.
@Raj, you can take a look at this tutorial https://www.codeofaninja.com/2013/04/android-http-client.html
Of you will use GET, you can just modify your URL. If you will use POST, you have to play with key-value pairs.
ohh it is not work
Great tutorial, however, i am compiling with api 23 and the parser has deprecated code. What is the alternative?
can i use Json model class to login if you have example please share
@ebinfrancis:disqus we will work on that example soon!
Hi, Is it possible generate json string from android?