How To Parsing Json Object Using Gson In Android Tutorial

Please follow and like us:

json object parsing

 

GSON is open source and standalone library which is used to convert JSON data into java objects and vice versa. It provides two methods fromJson()  -“ convert JSON format to java objects” and  toJson()  – “create JSON from java objects”. In previous tutorial we have seen about “How To Parsing Json Array Using Gson In Android Tutorial”. In this tutorial we are going to discuss about JSON parsing for JSON Object formats using GSON Library.

How To Parsing Json Object Using Gson In Android Tutorial

Parse JSON Object using GSON library

JSON format: URL

{
   "topics":[
      {
         "title":"how to add fontawesome icons in android example"
      },
      {
         "title":"how to parse json parsing using gson library"
      },
      {
         "title":"how to store arraylist in sharedpreferences"
      }
   ],
   "auther":"nirav kalola",
   "price":"free",
   "subject":"Android Application Development Tutorial"
}

In JSON, “[” stands for JSON Array and “{” stands for JSON Object.
We need to create one model class “Beansubject” & ”BeanTopic” 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;
import java.util.ArrayList;
public class BeanSubject {

    @SerializedName("subject")
    private String subject;
    @SerializedName("price")
    private String price;
    @SerializedName("auther")
    private String auther;
    @SerializedName("topics")
    private ArrayList<BeanTopic> beanTopics;

    public BeanSubject(ArrayList<BeanTopic> beanTopics, String subject, String price, String auther) {
        this.beanTopics = beanTopics;
        this.subject = subject;
        this.price = price;
        this.auther = auther;
    }

    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getAuther() {
        return auther;
    }
    public void setAuther(String auther) {
        this.auther = auther;
    }
    public ArrayList<BeanTopic> getBeanTopics() {
        return beanTopics;
    }
    public void setBeanTopics(ArrayList<BeanTopic> beanTopics) {
        this.beanTopics = beanTopics;
    }
}

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

    @SerializedName("title")
    private String title;

    public BeanTopic(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

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/OkS85Le");
                beanSubject = new GsonBuilder().create().fromJson(reader, BeanSubject.class);
                Log.e("Subject: ", beanSubject.getSubject()+"");
                Log.e("Auther: ", beanSubject.getAuther()+"");
                Log.e("Price: ", beanSubject.getPrice()+"");
                topicArrayList=beanSubject.getBeanTopics();
                topicList=new StringBuffer();
                for(BeanTopic topic: topicArrayList){
                    Log.e("topic title: ",topic.getTitle()+"");
                    topicList.append("* "+topic.getTitle()+"\n");
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                progressDialog.dismiss();
                txtSubject.setText("Subject: "+beanSubject.getSubject());
                txtPrice.setText("price: "+beanSubject.getPrice());
                txtAuther.setText("Auther: "+beanSubject.getAuther());
                txtTopicsList.setText("Topics: "+"\n"+topicList);
            }
        }.execute();

For parsing JSON object, we have to do a lot of work. But now with the help of GSON and POJO class, we can implement it very easily. Stay connected for latest android development tutorials for beginners.

nirav kalola