Você está na página 1de 16

11/1/2018 Android JSON Parsing Tutorial

     

BEGINNER

Android JSON Parsing Tutorial


BY RAVI TAMADA - JANUARY 21, 2012 - 879 CO MMENTS

JSON is very light weight, structured, easy to


parse and much human readable. JSON is
best alternative to XML when your android
app needs to interchange data with your
server. If your app consuming XML data, you
can always refer to Android XML Parsing
Tutorial.

In this tutorial we are going to learn how to


parse JSON in android using di erent ways,
using java.net library and other third part
libraries.

DOWNLOAD CODE DOWNLOAD .APK

The Sample JSON

Following is the sample JSON that we are going to parse in this tutorial. This is very simple
JSON which gives us list of contacts where each node contains contact information like
name, email, address, gender and phone numbers.

You can get this JSON data by accessing https://api.androidhive.info/contacts/

{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 1/16
11/1/2018 Android JSON Parsing Tutorial
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
.
]
}

The di erence between [ and { – (Square brackets and


Curly brackets)

In general all the JSON nodes will start with a square bracket or with a curly bracket. The
di erence between [ and { is, the square bracket ([) represents starting of an JSONArray
node whereas curly bracket ({) represents JSONObject. So while accessing these nodes
we need to call appropriate method to access the data.

If your JSON node starts with [, then we should use getJSONArray() method. Same as if
the node starts with {, then we should use getJSONObject() method.

1. Creating New Project

So let’s start by creating a new android project. We’ll build a simple app which fetches the
json from url, parses it and displays the contacts in a list view. Here we’ll use import
java.net libraries (which are natively supported in android) to make the http call and fetch
the json from url.

1. Create a new project in Android Studio from File ⇒ New Project and ll out the
required details.

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 2/16
11/1/2018 Android JSON Parsing Tutorial

2. As we are fetching the JSON by making HTTP calls, we need to add INTERNET
permission in AndroidManifest.xml le. Open AndroidManifest.xml and add the
following permission.

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

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.jsonparsing" >

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCH
</intent-filter>
</activity>
</application>

</manifest>

3. Create a class named HttpHandler.java and use the below code. Here
makeServiceCall() makes http call to particular url and fetches the response. In our case,
we use this to get the raw json from the url.

HttpHandler.java
package info.androidhive.jsonparsing;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
* Created by Ravi Tamada on 01/09/16.
* www.androidhive.info
*/
public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName(

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 3/16
11/1/2018 Android JSON Parsing Tutorial
public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {


String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConne
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStre
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}

private String convertStreamToString(InputStream is) {


BufferedReader reader = new BufferedReader(new InputStreamRead
StringBuilder sb = new StringBuilder();

String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

4. Before making the http call, let’s add a list view rst in our view. Open the layout le of
main activity (activity_main.xml) and add a ListView element.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.jsonparsing.MainActivity">

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 4/16
11/1/2018 Android JSON Parsing Tutorial

5. Create another layout le named list_item.xml with following content. This will be used
to render single list item view.

list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/androi
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">

<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />

<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/colorAccent" />

<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>

6. Open MainActivity.java and declare the necessary variables for the list view. If you
haven’t worked with list view yet, Android ListView Tutorial will helps you in getting
started.

MainActivity.java
public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 5/16
11/1/2018 Android JSON Parsing Tutorial

private ProgressDialog pDialog;


private ListView lv;

// URL to get contacts JSON


private static String url = "https://api.androidhive.info/contacts

ArrayList<HashMap<String, String>> contactList;

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

contactList = new ArrayList<>();

lv = (ListView) findViewById(R.id.list);
}
}

1.1 Downloading & Parsing the JSON

7. As we are getting the JSON by making HTTP call, I am adding a Async class GetContacts
to make http calls on background thread. Add the following method in your main activity
class.

In onPreExecute() method progress dialog is shown before making the http call.

In doInBackground() method, makeServiceCall() is called to get the json from url. Once
the json is fetched, it is parsed and each contact is added to array list.

In onPostExecute() method the progress dialog is dismissed and the array list data is
displayed in list view using an adapter.

Also note that I have used getJSONArray() or getJSONObject() method depending on the
type of node.

MainActivity.java
package info.androidhive.jsonparsing;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 6/16
11/1/2018 Android JSON Parsing Tutorial
private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;


private ListView lv;

// URL to get contacts JSON


private static String url = "https://api.androidhive.info/contacts

ArrayList<HashMap<String, String>> contactList;

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

contactList = new ArrayList<>();

lv = (ListView) findViewById(R.id.list);

new GetContacts().execute();
}

/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response


String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node


JSONArray contacts = jsonObj.getJSONArray("contact

// looping through All Contacts


for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");

// Phone node is JSON Object


JSONObject phone = c.getJSONObject("phone");

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 7/16
11/1/2018 Android JSON Parsing Tutorial
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");

// tmp hash map for single contact


HashMap<String, String> contact = new HashMap<

// adding each child node to HashMap key => va


contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);

// adding contact to contact list


contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage()
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMess
Toast.LENGTH_LONG)
.show();
}
});

}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check
Toast.LENGTH_LONG)
.show();
}
});

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});

lv.setAdapter(adapter);
}

}
}

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 8/16
11/1/2018 Android JSON Parsing Tutorial

If you run the project, you can see json data populated into list view as shown in the
below image.

2. Json Parsing using Library

The above method is very easy for simpler json. If the json is very complex, it is better to
consider the third party libraries as they are much faster and reliable. Below are the
popular libraries used to parse the json.

2.1 Using Volley Library

Volley HTTP library provides easy way to make networks calls. In Android JSON parsing
using Volley you can learn how to do that same in easy way using volley networking library
which provides you lot of advantages like success/error callback methods and cache
options.

2.2 Using Retro t Library

Retro t is much popular than volley. The parsing is done using jackson libraries in which
you just have to create models for json nodes and the library automatically converts the
json into appropriate objects. Go through Android Working with Retro t HTTP Library
which explains in detail about retro t library.

Change Log

Updated On 27th Dec 2013 (Content Update, Bug xes)

1st Sep 2016 (Content Update, Bug xes, latest libraries)

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 9/16
11/1/2018 Android JSON Parsing Tutorial

Ravi Tamada
Ravi is hardcore Android programmer and Android programming
has been his passion since he compiled his rst hello-world
program. Solving real problems of Android developers through
tutorials has always been interesting part for him.

You Might Also Like

Most Awkward Prom Photos Ever Captured

14 Hot Celebs Who Got Really Fat

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 10/16
11/1/2018 Android JSON Parsing Tutorial

The 11 Worst Tourist Photos Ever Will Leave You Speechless

21 Epic Perfectly Timed Photos You Just Can't Miss

17 Epic Perfectly Timed Photos You Can't Miss

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 11/16
11/1/2018 Android JSON Parsing Tutorial

35 Photos That Were Timed So Perfect!

24 Celebrities That Grew Up to Be Insanely Hot

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 12/16
11/1/2018 Android JSON Parsing Tutorial

You Had One Job - Epic Construction Fails

What Is Net Neutrality and Why Are People Freaking Out?

ASYNC B E G I NNER HTTP JSON LIST VIEW R E T R OFIT

V O L L EY

RELATED POSTS

Android Easy Runtime Permissions with Dexter

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 13/16
11/1/2018 Android JSON Parsing Tutorial

Android Working with Bottom Navigation

Android RecyclerView adding Search Filter

110 Comments Android Hive 


1 Login

Sort by Newest
 Recommend 130 ⤤ Share

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Ajay Kulkarni • a day ago


Hello, Ravi....

That was good tutorial. However there was an error in my Android Studio 3.0.1:
When I extended AsyncTask in MainActivity.java as you told, I get this error: Error:(48,
45) error: illegal start of type.
Help me to fix it.
△ ▽ • Reply • Share ›

Ravi Tamada Mod > Ajay Kulkarni • 16 hours ago

Could you post the code?


△ ▽ • Reply • Share ›

emi • 4 days ago


https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 14/16
11/1/2018 Android JSON Parsing Tutorial
emi 4 days ago
Thanks for the tutorial i have a question how to make a onClickListener in order to
open something when the user clicks on one of the contact names?
△ ▽ • Reply • Share ›

Ravi Tamada Mod > emi • 4 days ago

Just write on click listener for your list view and pass the contact via intent to
another activity.
△ ▽ • Reply • Share ›

emi > Ravi Tamada • 4 days ago


can you provide me the source code ? I dont understand it sorry
△ ▽ • Reply • Share ›

Deependra • 4 days ago


I am trying to put putExtra value from MainActivity.java inside URL on second screen
that is CropnameActivity.java
MainActivity.java contains following relevant part of code
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, cropcategoryList,
R.layout.list_item, new String[]{"cropCategoryName"}, new int[]
{R.id.cropCategoryName});

lv.setAdapter(adapter);

lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
Intent cropcategoryIntent = new Intent(MainActivity.this, CropnameActivity.class);

String cropCategoryName = ((TextView)


view.findViewById(R.id.cropCategoryName)).getText().toString();
cropcategoryIntent.putExtra("cropCategoryName", cropCategoryName);

see more

△ ▽ • Reply • Share ›

Deependra • 6 days ago


I am beginner at android development and started learning about a fortnight ago. I
tried your tutorial and the code worked perfectly yesterday. I was able to parse json
data.
Now if I want to create second screen and show other contact details of selected
person in listview, how to do it. for example, if I click Ravi Tamada on screen, it should
take the user to another screen with all other Ravi Tamada's contact details
separately in list view. How to do it?
For my purpose I am using following json webservice
http://dsy.impras.in/food/a...
I want to create three screens;
Screen 1: Listview of all cropName (here in api written as cucumber)
Screen 2: Listview of foodName with reference to cropName selected on Screen 1
Screen 3: Listview of majorFoodName with reference to foodName selected from
Screen 2
Kindly help
△ ▽ • Reply • Share ›

Ravi Tamada Mod > Deependra • 6 days ago

Hi Deependra

You can do this very easily.

1. First of all use RecyclerView to display the information in list. Don't use the
ListView. This article can help in displaying json data in list (ignore search
part).
https://www.androidhive.inf...

2. Second you need to find the item that is clicked. You can attach a click
listener to RecyclerView and find the item index selected. Once index is
known, you can get the item details from the ArrayList.
https://www.androidhive.inf... You can learn RecyclerView and Click listener
here.

https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 15/16
11/1/2018 Android JSON Parsing Tutorial
3. Pass the selected item id or name (whatever parameter is required to get
complete json of a single item). You can pass the data to another activity via
intents.
https://www.androidhive.inf... This article explains how to send data b/w
activities via intents.

4. On the full details activity, get the item id sent from list activity and fetch the
json by making http call again.
△ ▽ • Reply • Share ›

Deependra > Ravi Tamada • 6 days ago


Thanks for help
△ ▽ • Reply • Share ›

emi • 6 days ago


JSON Parsing error value <html> of type java.lang.string cannot be converted to
JSONObject
The error shows after installing and running your app provided in this article. Can you
solve it?
△ ▽ • Reply • Share ›

Ravi Tamada Mod > emi • 6 days ago

Are you trying the below url? The json is loading properly.
https://api.androidhive.inf...

If you are trying any other url, it is not responding with json. Instead it has
some errors.
△ ▽ • Reply • Share ›

emi > Ravi Tamada • 6 days ago


no im trying from the same url. Maybe the code it's not working can you
try to install the app?
△ ▽ • Reply • Share ›

Ravi Tamada Mod > emi • 6 days ago

Are you trying the the url with https, not http?

△ ▽ • Reply • Share ›

emi > Ravi Tamada • 4 days ago


I just download your apk from the source but it's not working
when i open the app
△ ▽ • Reply • Share ›

Ravi Tamada Mod > emi • 4 days ago

Yeah probably the apk still pointing to http url.


△ ▽ • Reply • Share ›

Aleks Kosyrev • 15 days ago


Just faced with exeption "Json parsing error: Value null at percent_change_7d of type
org.json.JSONObject$1 cannot be converted to int" How can I edit HttpHandler class
to avoid it? Making String response = ""; instead of null not worked.
△ ▽ • Reply • Share ›

Ravi Tamada Mod > Aleks Kosyrev • 15 days ago

Are you parsing the same response provided in the article?


△ ▽ • Reply • Share ›

Aleks Kosyrev > Ravi Tamada • 12 days ago


No, error has dissapiared. Think problem was at server side
△ ▽ • Reply • Share ›

Ravi Tamada Mod > Aleks Kosyrev • 12 days ago

Okay
△ ▽ • Reply • Share ›

Aleks Kosyrev • 18 days ago


Good day to you Ravi!
Thanks a lot for this tutorial. Found this very usefull for my app, also found so much
https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 16/16