Monday, 8 July 2013

JSON Web Service Call and Parsing Android


JSON Web Service Call and Parsing Android

Hi guys Today we will see JSON Web service Call and Response Parsing

Here we used jackson-core-asl-1.9.11.jar and
jackson-mapper-asl-1.9.11.jar

here is just sample code,

package com.example.webserviecexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {
       Context context;
       /**
        * * @author Khurram
        */
       private static String requestJson = null;

       /**
        * Named Constants at one location
        *
        * @author Khurram
        *
        */
       public enum ACTIONS {
              signIn, updateUserDetails, logout
       }

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

              /**
               * NetworkOnMainThreadException Temporary Solution
               */
              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                           .permitAll().build();
              StrictMode.setThreadPolicy(policy);

              /**
               * String response is return resultant Json string which we need to
               * parse
               */
              String response = signIn("9175390247", "12345");

              Toast.makeText(getApplicationContext(), response, 1).show();

       }

       public String signIn(String phoneNo, String password) {
              /**
               * create HasMap with key As String And Value As Object so You can store
               * complex data such as another hashMap as value of key.
               */
              Map<String, Object> request = new HashMap<String, Object>();

              /**
               * put Keys and values in Map
               */
              request.put("action", ACTIONS.signIn.toString());
              request.put("phoneNo", phoneNo);
              request.put("password", password);

              requestJson = buildRequestJson(request);

              Log.e("requestJson", "" + requestJson);

              String response = webServiceCall(context, ACTIONS.signIn.toString(),
                           requestJson);

              return response;
       }
       public String buildRequestJson(Map<String, Object> request) {

              /**
               * Create the object of jackson.map.ObjectMapper class
               */

              ObjectMapper mapper = new ObjectMapper();
              String json = null;

              try {
                     /**
                      * writeValueAsString() This method will convert our map object into
                      * json String
                      *
                      * */

                     json = mapper.writeValueAsString(request);
              } catch (JsonGenerationException e) {
                     e.printStackTrace();
              } catch (JsonMappingException e) {
                     e.printStackTrace();
              } catch (IOException e) {
                     e.printStackTrace();
              }
              /**
               * example like
               * {"phoneNo":"9175390247","action":"signIn","password":"12345"}
               */

              return json;

       }

       public String webServiceCall(Context context, String action, String request) {
              String response = null;
              InputStream is = null;
              try {
                     /**
                      * Represents a collection of HTTP protocol and framework
                      * parameters.
                      */
                     HttpParams httpParameters = new BasicHttpParams();
                     // Set the timeout in milliseconds until a connection is
                     // established.
                     int timeoutConnection = 10000;
                     /**
                      * Sets the timeout until a connection is etablished. A value of
                      * zero means the timeout is not used. The default value is zero.
                      */
                     HttpConnectionParams.setConnectionTimeout(httpParameters,
                                  timeoutConnection);
                     // Set the default socket timeout (SO_TIMEOUT)
                     // in milliseconds which is the timeout for waiting for data.
                     int timeoutSocket = 50000;
                     /**
                      * Sets the default socket timeout (SO_TIMEOUT) in milliseconds
                      * which is the timeout for waiting for data. A timeout value of
                      * zero is interpreted as an infinite timeout. This value is used
                      * when no socket timeout is set in the method parameters.
                      */
                     HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                     /**
                      * Default implementation of an HTTP client.
                      */
                     DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                     // HttpPost httpPost = new HttpPost(
                     // "http://192.168.2.8:8081/apps/mobile/" + action
                     // + ".action");
                     // http://192..168.56.101:8080/apps/gobz/showBusHomePage.action

                     /**
                      * The POST method is used to request that the origin server accept
                      * the entity enclosed in the request as a new subordinate of the
                      * resource identified by the Request-URI in the Request-Line.
                      */

                     HttpPost httpPost = new HttpPost(
                                  "http://192..168.56.101:8080/apps/mobile/" + action
                                                + ".action");

                     Log.e("url", "http://192..168.56.101:8080/apps/mobile/"
                                  + action + ".action");

                     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

                     nameValuePairs.add(new BasicNameValuePair("requestJson", request));

                     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

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

              } catch (ClientProtocolException e) {
                     // response = "ClientProtocolException";
                     e.printStackTrace();
              } catch (IOException e) {
                     e.printStackTrace();
                     // response = "IOException";
              } catch (Exception e) {
                     e.printStackTrace();
                     // response = "UnExpectedException";
              }
              // converting input stream to string response

              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();
                     response = sb.toString();
              } catch (Exception e) {
                     Log.e("Buffer Error", "Error converting result " + e.toString());
              }
              if (response != null)
                     Log.e("response in AsyncRequestResponseJsonService", response);

              return response;
       }

       public Object parseSignInResponse(String response) {
              /**
               * Always create your business object references only
               */
              UserDetails userDeatials = null;

              JSONObject jObj = parseTag(response, context);
              if (jObj != null) {

                     /**
                      * Always initialize your business object references on Valid Json
                      * Object
                      */
                     userDeatials = new UserDetails();
                     /**
                      * use tray catch for parsing your element and in catch show error
                      * as "ParseDataException in Success responseJson"
                      */
                     try {
                           if (jObj.has("cosnumerKey"))
                                  userDeatials.setAppUser(jObj.getString("cosnumerKey"));

                           if (jObj.has("socUsrId"))
                                  userDeatials.setSocialLabelId(jObj.getString("socUsrId"));

                           if (jObj.has("securityToken"))
                                  userDeatials.setSecurityToken(jObj
                                                .getString("securityToken"));

                           if (jObj.has("requestForMobile"))
                                  userDeatials.setRequestForMobile(jObj
                                                .getString("requestForMobile"));

                           return userDeatials;
                     } catch (JSONException e) {
                           /**
                            * always return null from catch so no raw data will be save
                            */
                           e.printStackTrace();
                           Toast.makeText(context, "parse_data_exception_in_success", 1)
                                         .show();
                           return null;
                     }
              }
              /**
               * return your Business Object
               */
              return userDeatials;
       }

       public static JSONObject parseTag(String response, Context context) {

              String myExceptions = null;
              JSONObject jsonObject = null;

              /**
               * Every web service response may contains 5 elements
               * ClientProtocolException IOException UnExpectedException
               * ErrorConvertingResult null so it take action according that and show
               * message Dialog and if response contains "Valid Response" then it
               * return as it is
               */
              if (response != null && response.length() > 0) {

                     if (response.equalsIgnoreCase("ClientProtocolException")) {
                           myExceptions = "ClientProtocolException";
                     } else if (response.equalsIgnoreCase("IOException")) {
                           myExceptions = "IOException";
                     } else if (response.equalsIgnoreCase("UnExpectedException")) {
                           myExceptions = "UnExpectedException";
                     } else if (response.equalsIgnoreCase("ErrorConvertingResult")) {
                           myExceptions = "ErrorConvertingResult";
                     } else {
                           /**
                            * if response contain valid data then send to parser class
                            * static method with appropriate context and then it returns
                            * Business object as a parameter to your loadData method witch
                            * populate your data to screen elements
                            */
                           // No Exception, Response Is available to use,
                           // we parse response
                           try {
                                  jsonObject = new JSONObject(response);
                                  if (jsonObject.has("responseJson")) {
                                         String jsonResponse = jsonObject
                                                       .getString("responseJson");
                                         JSONObject jObj = new JSONObject(jsonResponse);
                                         if (jObj.has("result")) {
                                                if (jObj.getString("result").equalsIgnoreCase(
                                                              "SUCCESS")) {
                                                       // TODO please use all posible combinitions of
                                                       // success
                                                       // responses
                                                       // ////////////////////////////////////////////
                                                       return jObj;
                                                       // /////////////////////////////////////////////
                                                } else if (jObj.getString("result")
                                                              .equalsIgnoreCase("error")) {
                                                       myExceptions = "Result : "
                                                                     + jObj.getString("result")
                                                                     + "\nError Details : "
                                                                     + jObj.getString("errorDetails")
                                                                     + "\nError Condition : "
                                                                     + jObj.getString("errorCondition");
                                                } else {
                                                       // TODO
                                                       // read just for testing perpuse later should be
                                                       // removed
                                                       myExceptions = " Unexpected Data Response : Result = "
                                                                     + jObj.getString("result");
                                                }
                                         } else {
                                                myExceptions = "Unexpected Data Response, No Result tag Found";
                                         }
                                  } else {
                                         myExceptions = "Unexpected Data Response, No responseJson tag Found";
                                  }
                           } catch (JSONException e) {
                                  e.printStackTrace();
                                  myExceptions = "null_response";
                           }

                     }// exception handling else

                     if (myExceptions != null) {
                           Toast.makeText(context, myExceptions, 1).show();
                     }
              } else {
                     Toast.makeText(context, "Null Response", 1).show();
              }
              /**
               * else call loadData with null as a parameter so load data will decide
               * to show offline data on getting null there
               */

              return null;

       }


}


The good and Short Thing is that 
You can download complete working example from here :)


Happy Codddding :)



No comments:

Post a Comment