Android: Deserialize both XML and JSON


When I first started learning Android, I was curious in making service calls and handling the results.  Naturally, I wanted to see code snippets involving
  • parsing XML
  • deserializing JSON
To my surprise, most snippets I found only demonstrated XML parsing, with fewer demonstrating JSON deserialization.  Therefore, I decided to post these brief snippets in hopes they are useful to folks.
We’ll use a simple Employee class as an example.  If you are familiar with the term DTO, data transfer object, this Employee class represents a simple DTO.  The Java source code is as follows:
public class Employee {
    public long Id;
    public long DeptId;
    public long SalaryGradeId;
    public String FirstName;
    public String LastName;
    public String Email;
    public String Phone;
    public String Title;
    public boolean TakesLongLunches;
}

And we’ll use the following ResourceHelper class to request a list of employees:
package com.demo.helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class ResourceHelper {
    public static String loadManySerialized(String url)
    {
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url);

        // Execute the request
        HttpResponse response;

        String result = null;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {
                // A Simple Response Read
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

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

        return sb.toString();
    } 
}

And here are two calls to ResourceHelper;  one requesting the response in XML format, and the other requesting the response in JSON:
String XMLSerializedResources = ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=XML"); 
String JSONSerializedResources = ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=JSON");
Next, we’ll parse the XML list within the Employee Repository with the help of an XMLHelper class (see line 24).  The XMLHelper class, also shown below, calls the ResourceHelper class we discussed earlier.

package com.demo.domainmodel.repository;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.demo.domainmodel.Employee;
import com.demo.helpers.XmlHelper;

public class EmployeeRepository
{
    public static ArrayList<Employee> loadMany(String url)
    {
        int parserEvent = -1;
        XmlPullParser parser = null;
        ArrayList<Employee> items = new ArrayList<Employee>();
        String tag = "";
        Employee item = null;

        try {
            // calls service (referenced in url) to request XML serialized data
            parser = XmlHelper.loadData(url);
            parserEvent = parser.getEventType();

            while (parserEvent != XmlPullParser.END_DOCUMENT) {
                switch(parserEvent) {
                  case XmlPullParser.START_TAG:
                      tag = parser.getName();
                      if (tag.compareTo("Employee") == 0){
                          item = new Employee();
                      }
                  break;
                  case XmlPullParser.END_TAG:
                      tag = parser.getName();
                      if (tag.compareTo("Employee") == 0){
                          items.add(item);
                      }
                  break;
                  case XmlPullParser.TEXT:
                      String text = parser.getText();
                      if (text.trim().length() == 0) break;

                      if (tag.compareTo("Id") == 0){
                          item.Id = Integer.parseInt(text);
                      }
                      else if (tag.compareTo("DeptId") == 0){
                          item.DeptId = Integer.parseInt(text);
                      }
                      else if (tag.compareTo("SalaryGradeId") == 0){
                          item.SalaryGradeId = Integer.parseInt(text);
                      }
                      else if(tag.compareTo("FirstName") == 0){
                          item.FirstName = text;
                      }
                      else if(tag.compareTo("LastName") == 0){
                          item.LastName = text;
                      }
                      else if(tag.compareTo("Email") == 0){
                          item.Email = text;
                      }
                      else if(tag.compareTo("Phone") == 0){
                          item.Phone = text;
                      }
                      else if(tag.compareTo("Title") == 0){
                          item.Title = text;
                      }
                      else if(tag.compareTo("TakesLongLunches") == 0){
                          item.TakesLongLunches = Boolean.parseBoolean(text);
                      }

                  break;
                }

                parserEvent = parser.next();
            }
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // return de-serialized list of employees
        return items;
    }
}

package com.demo.helpers;

import java.io.*;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class XmlHelper {
    public static XmlPullParser loadData(String url) throws XmlPullParserException, IOException
    {
        String xmlData = ResourceHelper.loadManySerialized(url);

        XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = parserFactory.newPullParser();
        parser.setInput(new StringReader(xmlData));

        return parser;
    } 
}
To call the EmployeeRepository to obtain an actual list of Employee objects, simply use the following:
ArrayList<Employee> employees = EmployeeRepository.loadMany("http://demos.brianbuikema.com/apps/soa_services/employees?format=XML");

And finally, we’ll deserialize the JSON list.  Please pay special attention as the Employee class has been modified to do its own deserialization/serialization.  I use a static method deserializeArray(…) from within the Employee class, passing it the JSON results from the call toResourceHelper.loadManySerialized(…):
package com.hd.domainmodel;

import java.util.ArrayList;

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

public class Employee {
    public long Id;
    public long DeptId;
    public long SalaryGradeId;
    public String FirstName;
    public String LastName;
    public String Email;
    public String Phone;
    public String Title;
    public boolean TakesLongLunches;

    public Employee() {
    }

    public Employee(JSONObject obj) throws JSONException {
        deserializeFromObj(obj);
    }

    public Employee(String serializedObj) throws JSONException {
        deserialize(serializedObj);
    }

    public void deserialize(String serializedObj) throws JSONException {
        JSONObject obj = new JSONObject(serializedObj);
        deserializeFromObj(obj);
    }

    public void deserializeFromObj(JSONObject obj) throws JSONException {
        this.Id = obj.getLong("Id");
        this.DeptId = obj.getLong("DeptId");
        this.SalaryGradeId = obj.getLong("SalaryGradeId");
        this.FirstName = obj.getString("FirstName");
        this.LastName = obj.getString("LastName");
        this.Email = obj.getString("Email");
        this.Phone = obj.getString("Phone");
        this.Title = obj.getString("Title");
        this.TakesLongLunches = Boolean.parseBoolean(obj.getString("TakesLongLunches"));
    }

    public String serialize() throws JSONException {
        return serializeToObj().toString();
    }

    public JSONObject serializeToObj() throws JSONException {
        JSONObject serializedObj = new JSONObject();
        serializedObj.put("Id", this.Id);
        serializedObj.put("DeptId", this.DeptId);
        serializedObj.put("SalaryGradeId", this.SalaryGradeId);
        serializedObj.put("FirstName", this.FirstName);
        serializedObj.put("LastName", this.LastName);
        serializedObj.put("Email", this.Email);
        serializedObj.put("Phone", this.Phone);
        serializedObj.put("Title", this.Title);
        serializedObj.put("TakesLongLunches", this.TakesLongLunches);

        return serializedObj;
    }

    public static ArrayList<Employee> deserializeArray(String serializedArray) throws JSONException {
        JSONArray jsonObjs = new JSONArray(serializedArray);
        ArrayList<Employee> employees = new ArrayList<Employee>();
        for (int i=0; i<jsonObjs.length(); i++) {
            JSONObject employee = jsonObjs.getJSONObject(i);
            employees.add(new Employee(employee));
        }

        return employees;
    } 
}
o retrieve a list of employee objects, we’ll call the Employee.deserializeArray(…), passing it the serialized String obtained by calling ResourceHelper.loadManySerialized(…).
ArrayList<Employee> employees = Employee.deserializeArray(ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=JSON"));
This article comes from Brian Buikema

 
 
 
 
 

1 comment:

Dengan mengirim komentar disini, Anda menyetujui bahwa komentar anda tidak mengandung Rasis ataupun konten pornografi