How To Parsing Json Array Using Gson In Android Tutorial

Please follow and like us:

json array parsing

 

JSON-“JavaScript Object Notation” is very well structured, light weight and easy to parse. It is the best alternative for XML. For automatic JSON parsing we are going to use Google GSON library. GSON is open source library which is used to convert JSON data into java objects and vice versa. GSON can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.  It provides two methods fromJson()  -“ convert JSON format to java objects” and  toJson()  – “create JSON from java objects”. In this tutorial we are going to discuss about JSON parsing for JSON Array formats using GSON Library.

How To Parsing Json Array Using Gson In Android Tutorial

Parse JSON Array using GSON Library

JSON format: URL

[
   {
      "date":"11/8/2014",
      "auther":"nirav kalola",
      "description":"json object parsing using gson library is easy",
      "post_name":"json object parsing"
   },
   {
      "date":"12/8/2014",
      "auther":"nirav kalola",
      "description":"json array parsing using gson library",
      "post_name":"json array parsing"
   },
   {
      "date":"17/8/2014",
      "auther":"nirav kalola",
      "description":"store json file in assets folder and get data when required",
      "post_name":"json parsing from assets folder"
   }
]

In JSON, “[” stands for JSON Array and “{” stands for JSON Object. In our example we have one JSON Array and three JSON Objects.
We need to create one model class “BeanPost” and annotate field names with the SerializedName annotation. When we add serialized name to field must match with key name from JSON.

import com.google.gson.annotations.SerializedName;
public class BeanPost {

    @SerializedName("post_name")
    private String post_name;
    @SerializedName("auther")
    private String auther;
    @SerializedName("date")
    private String date;
    @SerializedName("description")
    private String description;

    public BeanPost(String post_name, String auther, String date, String description) {
        this.post_name = post_name;
        this.auther = auther;
        this.date = date;
        this.description = description;
    }

    public String getPost_name() {
        return post_name;
    }
    public void setPost_name(String post_name) {
        this.post_name = post_name;
    }
    public String getAuther() {
        return auther;
    }
    public void setAuther(String auther) {
        this.auther = auther;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

Create API.java class to perform an HTTP request and retrieve the resource as a stream.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class API {
   private static Reader reader=null;

   public static Reader getData(String SERVER_URL) {
  try {
   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(SERVER_URL);
   HttpResponse response = httpClient.execute(httpPost);
   StatusLine statusLine = response.getStatusLine();

   if (statusLine.getStatusCode() == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       reader = new InputStreamReader(content);
    } else {
//  Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
    }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
          e.printStackTrace();
    }
    return reader;
    }

}

Create MainActivity.java Activity class and create GSON instance get data in required format.

new AsyncTask<Void,Void,Void>(){

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog=new ProgressDialog(MyActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... voids) {
          Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");

                Type listType = new TypeToken<ArrayList<BeanPost>>(){}.getType();
                beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);

                postList=new StringBuffer();
                for(BeanPost post: beanPostArrayList){
                postList.append("\n title: "+post.getPost_name()+
                                "\n auther: "+post.getAuther()+
                                "\n date: "+post.getDate()+
                                "\n description: "+post.getDescription()+"\n\n");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                progressDialog.dismiss();
                txtPostList.setText(postList);
            }
        }.execute();

Parsing JSON array is very difficult task but using GSON it becomes very simple and easy to implement. Hope you like our simple tutorial about GSON library usage.

nirav kalola