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
http://code.google.com/p/google-gson/downloads/list

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:
{"success":false}

Source for MySQL data connection resource context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"
name="jdbc/mysql"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"
username="root"
password="mysql"
maxIdle="10"
maxActive="200"
maxWait="5"
removeAbandoned="true"
removeAbandonedTimeout="1200"
/>
</Context>

Source for Web application config file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AndroidJSONWebService</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>Country Servlet</description>
    <display-name>CountryServlet</display-name>
    <servlet-name>CountryServlet</servlet-name>
    <servlet-class>com.as400samplecode.CountryServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CountryServlet</servlet-name>
    <url-pattern>/CountryServlet</url-pattern>
  </servlet-mapping>
  <resource-ref>
    <description>MySQL Datasource</description>
    <res-ref-name>jdbc/mysql</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
  </resource-ref>
</web-app>

Source for Country object Java bean Country.java

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) {
        this.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 CountryInformation.java

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);
            stmt.setString(1,code); 
            ResultSet rs = stmt.executeQuery(); 
           
            while(rs.next()){ 
                country.setCode(rs.getString("code").trim());
                country.setName(rs.getString("name").trim());
                country.setContinent(rs.getString("continent").trim());
                country.setRegion(rs.getString("region").trim());
                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()));
            }                                                                         

            rs.close();                                                               
            stmt.close();                                                             
            stmt = null;                                                              


            conn.close();                                                             
            conn = null;                                                   

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

        finally {                                                       

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

                stmt = null;                                            
            }                                                        

            if (conn != null) {                                      
                try {                                                   
                    conn.close();                                          
                } 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 CountryServlet.java

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;

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;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

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

    public CountryServlet() {
        super();
    }

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

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


        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        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);
            out.println(myObj.toString());
        }

        //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
            out.println(myObj.toString());
        }
        out.close();
    }
}

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.