(Tutorial Android) Parsing Json Using Gson


GSON yaitu library java yang dipakai untuk meng-convert objek java ke JSON atau sebaliknya. GSON mempunyai fungsi serialization dan deserialization. Serialization berfungsi merubah JSON string menjadi objek java, sedangkan deserialization berfungsi merubah objek java menjadi bentuk JSON. Serialization dan deserialization di GSON memakai fungsi fromJson() dan toJson().

Pada tutorial sebelumnya https://andronut.blogspot.com//search?q=tutorial-android-json-parsing-example saya menjelaskan bagaimana memparsing JSON secara konvensional memakai fungsi JSONObject dan JSONArray. Nah, pada postingan kali ini tidak jauh beda yakni memakai library GSON untuk parsing. Bentuk JSON yang dipakai sama dengan sebelumnya yakni berikut :

{      "firstName": "John",      "lastName": "Smith",      "age": 25,      "address":      {          "streetAddress": "21 2nd Street",          "city": "New York",          "state": "NY",          "postalCode": "10021"      },      "phoneNumber":      [          {            "type": "home",            "number": "212 555-1234"          },          {            "type": "fax",            "number": "646 555-4567"          }      ]  } 

Buat file dengan nama customer.json kemudian letakkan di folder assets project android kita.

Pertama, tambahkan dependencies GSON di gradle.
compile 'com.google.code.gson:gson:2.6.2' 

Tambahkan beberapa string resource di strings.xml
<resources>     <string name="app_name">Android-GSON</string>      <string name="first_name">First Name : %s</string>     <string name="last_name">Last Name : %s</string>     <string name="age">Age : %d</string>     <string name="address">Address :</string>     <string name="street">Street : %s</string>     <string name="city">City : %s</string>     <string name="state">State : %s</string>     <string name="postal_code">Postal Code : %s</string>     <string name="phone">Phone Number :</string>  </resources>  

Buat layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context="example.wim.androidgson.MainActivity">      <TextView         android:id="@+id/first_name"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/first_name" />      <TextView         android:id="@+id/last_name"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/last_name"         android:layout_below="@+id/first_name" />      <TextView         android:id="@+id/age"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/age"         android:layout_below="@+id/last_name" />      <TextView         android:id="@+id/address"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/address"         android:layout_below="@+id/age" />      <TextView         android:id="@+id/street"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/street"         android:layout_below="@+id/address"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>      <TextView         android:id="@+id/city"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/city"         android:layout_below="@+id/street"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>      <TextView         android:id="@+id/state"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/state"         android:layout_below="@+id/city"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>      <TextView         android:id="@+id/postal_code"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/postal_code"         android:layout_below="@+id/state"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>      <TextView         android:id="@+id/phone"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:text="@string/phone"         android:layout_below="@+id/postal_code"/>      <TextView         android:id="@+id/home"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:layout_below="@+id/phone"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>      <TextView         android:id="@+id/fax"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:padding="5dp"         android:textSize="15sp"         android:layout_below="@+id/home"         android:layout_marginLeft="@dimen/activity_horizontal_margin"/>  </RelativeLayout> 

Kemudian buat fungsi untuk membaca file dari assets. Buat kelas FileUtil.java
import android.content.Context;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;  /**  * Created by Wim on 6/11/16.  */ public class FileUtil {      public static String copyFromAssets(Context context, String filename){         StringBuilder buf = new StringBuilder();         InputStream json = null;         try {             json = context.getAssets().open(filename);             BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));             String str;              while ((str=in.readLine()) != null) {                 buf.append(str);             }              in.close();         } catch (IOException e) {             e.printStackTrace();         }          return buf.toString();     }  } 

Nah, langkah selanjutnya yang paling penting yaitu menciptakan kelas objek java dari bentuk JSON di atas.

Bentuk JSON :
{      "firstName": "John",      "lastName": "Smith",      "age": 25,      "address":      {          "streetAddress": "21 2nd Street",          "city": "New York",          "state": "NY",          "postalCode": "10021"      },      "phoneNumber":      [          {            "type": "home",            "number": "212 555-1234"          },          {            "type": "fax",            "number": "646 555-4567"          }      ]  }  

Bentuk objek kelas java :
private String firstName; private String lastName; private int age; private Address address; private List<Phone> phoneNumber; 

Objek di JSON dibentuk menjadi bentuk variabel atau objek di java, sedangkan Array di JSON dibentuk menjadi list.

Selengkapnya buat kelas dengan nama Customer.java
import java.util.List;  /**  * Created by Wim on 6/11/16.  */ public class Customer {      private String firstName;     private String lastName;     private int age;     private Address address;     private List<Phone> phoneNumber;      public Customer() {     }      public String getFirstName() {         return firstName;     }      public void setFirstName(String firstName) {         this.firstName = firstName;     }      public String getLastName() {         return lastName;     }      public void setLastName(String lastName) {         this.lastName = lastName;     }      public int getAge() {         return age;     }      public void setAge(int age) {         this.age = age;     }      public Address getAddress() {         return address;     }      public void setAddress(Address address) {         this.address = address;     }      public List<Phone> getPhoneNumber() {         return phoneNumber;     }      public void setPhoneNumber(List<Phone> phoneNumber) {         this.phoneNumber = phoneNumber;     } }  

Kemudian untuk objek address di JSON dibentuk menjadi kelas Address.java
/**  * Created by Wim on 6/11/16.  */ public class Address {      private String streetAddress;     private String city;     private String state;     private String postalCode;      public Address() {     }      public String getStreetAddress() {         return streetAddress;     }      public void setStreetAddress(String streetAddress) {         this.streetAddress = streetAddress;     }      public String getCity() {         return city;     }      public void setCity(String city) {         this.city = city;     }      public String getState() {         return state;     }      public void setState(String state) {         this.state = state;     }      public String getPostalCode() {         return postalCode;     }      public void setPostalCode(String postalCode) {         this.postalCode = postalCode;     } }  

Kemudian objek phoneNumber di JSON dibentuk menjadi kelas Phone.java
/**  * Created by Wim on 6/11/16.  */ public class Phone {      private String type;     private String number;      public Phone() {     }      public String getType() {         return type;     }      public void setType(String type) {         this.type = type;     }      public String getNumber() {         return number;     }      public void setNumber(String number) {         this.number = number;     } }  

Langkah terakhir yaitu melaksanakan parsing JSON ke kelas objek java. Untuk merubah bentuk JSON ke objek java memakai fungsi fromJson() berikut :
Gson gson = new Gson(); Customer customer = gson.fromJson(json, Customer.class); 

Caranya sangat mudah.

Sekarang tinggal melengkapi source codenya di MainActivity.java sebagai berikut :
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView;  import com.google.gson.Gson;  import java.util.List;  import example.wim.androidgson.model.Address; import example.wim.androidgson.model.Customer; import example.wim.androidgson.model.Phone; import example.wim.androidgson.util.FileUtil;  public class MainActivity extends AppCompatActivity {      TextView firstName;     TextView lastName;     TextView age;     TextView street;     TextView city;     TextView state;     TextView postalCode;     TextView home;     TextView fax;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          injectViews();         parsingJson();     }      private void injectViews(){         firstName = (TextView) findViewById(R.id.first_name);         lastName = (TextView) findViewById(R.id.last_name);         age = (TextView) findViewById(R.id.age);         street = (TextView) findViewById(R.id.street);         city = (TextView) findViewById(R.id.city);         state = (TextView) findViewById(R.id.state);         postalCode = (TextView) findViewById(R.id.postal_code);         home = (TextView) findViewById(R.id.home);         fax = (TextView) findViewById(R.id.fax);     }      private void parsingJson(){         String json = FileUtil.copyFromAssets(this.getApplicationContext(), "customer.json");          Gson gson = new Gson();         Customer customer = gson.fromJson(json, Customer.class);          firstName.setText(getResources().getString(R.string.first_name, customer.getFirstName()));         lastName.setText(getResources().getString(R.string.last_name, customer.getLastName()));         age.setText(getResources().getString(R.string.age, customer.getAge()));          // Address         Address address = customer.getAddress();          street.setText(getResources().getString(R.string.street, address.getStreetAddress()));         city.setText(getResources().getString(R.string.city, address.getCity()));         state.setText(getResources().getString(R.string.state, address.getState()));         postalCode.setText(getResources().getString(R.string.postal_code, address.getPostalCode()));          // Phone         List<Phone> phoneList = customer.getPhoneNumber();          home.setText(phoneList.get(0).getType() +" : "+phoneList.get(0).getNumber());         fax.setText(phoneList.get(1).getType() + " : "+phoneList.get(1).getNumber());     } }  

Build dan jalankan maka kesudahannya menyerupai berikut :


Source code lengkap sanggup dilihat di https://github.com/andronut/Android-GSON

Sekian dan agar bermanfaat
Happy Coding :)

Comments

Popular posts from this blog

Pewarnaan Objek Geometri Di Java 2D

Tugas Komplemen Terakhir

Konsep Oop Encapsulation