Android JSON parsing Tutorial using Java Servlet and MySQL database

In this tutorial we will make a HTTP post request to a WEB service that will return the response in JSON format. We are going to parse the JSON response and display the information on the Screen. This tutorial will cover the following topics ...
  • Connection to MySQL database
  • Creating JSON objects from Java objects using Google Gson
  • Java Servlet taking HTTP request and sending response in JSON format
  • Android application making a HTTP post request
  • Intent Service to help us make the HTTP request outside the scope of the main UI thread which is prohibited
  • Broadcast receiver to lets us know when we receive the response from the WEB Service
  • Parse JSON response and create Java objects from JSON objects
  • Display parsed JSON on the android screen

Before we start please download the Google Gson jar, A Java library to convert JSON to Java objects and vice-versa. Here is the link

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Gson provides simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa

Before we step into the Android programming let's create the WEB Service using Java Servlet and MySQL database. The Servlet takes a country code and returns information about that country. Make sure you add the Gson jar file in your project classpath(Java build path if your using eclipse or put it your Tomcat library)

Android JSON Web Service Tutorial using Java Servlet and MySQL database

Sample JSON response from the WEB Service

Valid country code response:
{"success":true,"countryInfo":{"code":"USA","name":"United States","continent":"North America","region":"North America","lifeExpectancy":77.1,"gnp":8510700.0,"surfaceArea":9363520.0,"population":278357000}}

Invalid country code response:

Source for MySQL data connection resource context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"

Source for Web application config file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">
    <description>Country Servlet</description>
    <description>MySQL Datasource</description>

Source for Country object Java bean

package com.as400samplecode.util;

public class Country {
    String code = null;
    String name = null;
    String continent = null;
    String region = null;
    Double lifeExpectancy = null;
    Double gnp = null;
    Double surfaceArea = null;
    int population = 0;
    public String getCode() {
        return code;
    public void setCode(String code) {
        this.code = code;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getContinent() {
        return continent;
    public void setContinent(String continent) {
        this.continent = continent;
    public String getRegion() {
        return region;
    public void setRegion(String region) {
        this.region = region;
    public Double getLifeExpectancy() {
        return lifeExpectancy;
    public void setLifeExpectancy(Double lifeExpectancy) {
        this.lifeExpectancy = lifeExpectancy;
    public Double getGnp() {
        return gnp;
    public void setGnp(Double gnp) {
        this.gnp = gnp;
    public Double getSurfaceArea() {
        return surfaceArea;
    public void setSurfaceArea(Double surfaceArea) {
        this.surfaceArea = surfaceArea;
    public int getPopulation() {
        return population;
    public void setPopulation(int population) {
        this.population = population;

Source for WEB Service utility program

package com.as400samplecode.util;

import java.sql.Connection;         
import java.sql.ResultSet;          
import java.sql.SQLException;       
import java.sql.PreparedStatement;  

import javax.naming.Context;        
import javax.naming.InitialContext; 
import javax.sql.DataSource;        

public class CountryInformation {           

    Connection conn = null;            
    PreparedStatement stmt = null;     
    String sql = null;
    public Country getInfo(String code) { 

        Country country = new Country();   

        try {      
            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); 

            sql = "Select * from COUNTRY where code = ?"; 
            stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery(); 
                country.setLifeExpectancy(rs.getString("lifeExpectancy") == null ? new Double(0) : Double.parseDouble(rs.getString("lifeExpectancy").trim()));
                country.setGnp(rs.getString("gnp") == null ? new Double(0)  : Double.parseDouble(rs.getString("gnp").trim()));
                country.setSurfaceArea(rs.getString("surfaceArea") == null ? new Double(0)  : Double.parseDouble(rs.getString("surfaceArea").trim()));
                country.setPopulation(rs.getString("population") == null ? 0 : Integer.parseInt(rs.getString("population").trim()));

            stmt = null;                                                              

            conn = null;                                                   

        catch(Exception e){System.out.println(e);}                      

        finally {                                                       

            if (stmt != null) {                                            
                try {                                                         
                } catch (SQLException sqlex) {                                
                    // ignore -- as we can't do anything about it here           

                stmt = null;                                            

            if (conn != null) {                                      
                try {                                                   
                } catch (SQLException sqlex) {                          
                    // ignore -- as we can't do anything about it here     

                conn = null;                                            

        return country;



Source for Java Servlet to accept WEB request

package com.as400samplecode;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.as400samplecode.util.Country;
import com.as400samplecode.util.CountryInformation;


public class CountryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public CountryServlet() {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");

        //country code coming from Android 
        String countryCode = request.getParameter("countryCode").trim();

        //get country information based on country code
        CountryInformation countryInformation = new CountryInformation();
        Country country = countryInformation.getInfo(countryCode);

        //if invalid country code 
        if(country.getCode() == null){
            JsonObject myObj = new JsonObject();
            myObj.addProperty("success", false);

        //if a valid country code was sent
        else {
            Gson gson = new Gson(); 
            //creates json from country object
            JsonElement countryObj = gson.toJsonTree(country);

            //create a new JSON object
            JsonObject myObj = new JsonObject();
            //add property as success
            myObj.addProperty("success", true);
            //add the country object
            myObj.add("countryInfo", countryObj);
            //convert the JSON to string and send back

Click here for next Chapter

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.