(Tutorial Android) Json Parsing Example
JSON yaitu akronim dari JavaScript Object Notation. JSON merupakan format data yang ringan, terstruktur dan gampang untuk di parsing dan lebih gampang dipahami. Format ini dibentuk menurut bab dari pemrograman JavaScript.
Pada umumnya, JSON memakai bentuk sebagai berikut :
Objek : objek yaitu sepasang nilai yang tidak terurut. Objek dimulai dengan kurung kurawal buka { dan kurung kurawal tutup }.
Array : kumpulan nilai yang berurut. Array dimulai dengan kurung kotak buka [ dan kurung kotak tutup ].
Perhatikan pola JSON berikut :
JSON Object ditandai dengan kurung kurawal {}. Sedangkan JSON Array di tandai dengan kurung kotak []. Pada tutorial kali ini kita akan mencoba bagaimana memparsing JSON di Android.
Pertama, buka folder main di project, lalu buat folder assets. Buat file dengan format JSON di bawah ini di folder assets dan berjulukan customer.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" } ] }
Tambahkan string resource berikut di values/strings.xml.
<resources> <string name="app_name">Android-JSONParsing</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 dengan nama 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="com.example.wim.android_jsonparsing.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>
Buat kelas java dengan nama CustomerTags.java. Di sini kita akan mendefinisikan tag-tag yang ada pada JSON.
/** * Created by Wim on 5/29/16. */ public class CustomerTags { public static simpulan String TAG_FIRSTNAME = "firstName"; public static simpulan String TAG_LASTNAME = "lastName"; public static simpulan String TAG_AGE = "age"; public static simpulan String TAG_ADDRESS = "address"; public static simpulan String TAG_STREET_ADDRESS = "streetAddress"; public static simpulan String TAG_CITY = "city"; public static simpulan String TAG_STATE = "state"; public static simpulan String TAG_POSTAL_CODE = "postalCode"; public static simpulan String TAG_PHONE = "phoneNumber"; public static simpulan String TAG_TYPE = "type"; public static simpulan String TAG_NUMBER = "number"; }
Buat kelas FileUtil.java yang berfungsi membaca file dari folder assets.
import android.content.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by Wim on 5/29/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(); } }
Cara memparsing JSON kita sanggup memakai kelas JSONObject dan JSONArray. Kelas JSONObject berfungsi untuk memparsing JSON yang bertipe Object, sedangkan kelas JSONArray berfungsi untuk memparsing JSON yang bertipe Array.
String json = FileUtil.copyFromAssets(this.getApplicationContext(), "customer.json"); try { JSONObject jsonObj = new JSONObject(json); String objFirstName = jsonObj.getString(CustomerTags.TAG_FIRSTNAME); String objLastName = jsonObj.getString(CustomerTags.TAG_LASTNAME); int objAge = jsonObj.getInt(CustomerTags.TAG_AGE); // Address JSONObject objAddress = jsonObj.getJSONObject(CustomerTags.TAG_ADDRESS); String objStreet = objAddress.getString(CustomerTags.TAG_STREET_ADDRESS); String objCity = objAddress.getString(CustomerTags.TAG_CITY); String objState = objAddress.getString(CustomerTags.TAG_STATE); String objPostalCode = objAddress.getString(CustomerTags.TAG_POSTAL_CODE); // Phone Number JSONArray arrPhone = jsonObj.getJSONArray(CustomerTags.TAG_PHONE); String[] type = new String[arrPhone.length()]; String[] number = new String[arrPhone.length()]; for (int i = 0; i < arrPhone.length(); i++){ JSONObject objPhone = arrPhone.getJSONObject(i); type[i] = objPhone.getString(CustomerTags.TAG_TYPE); number[i] = objPhone.getString(CustomerTags.TAG_NUMBER); } } catch (JSONException e) { e.printStackTrace(); }
Berikut source lengkapnya di MainActivity.java.
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.example.wim.android_jsonparsing.tags.CustomerTags; import com.example.wim.android_jsonparsing.util.FileUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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"); try { JSONObject jsonObj = new JSONObject(json); String objFirstName = jsonObj.getString(CustomerTags.TAG_FIRSTNAME); String objLastName = jsonObj.getString(CustomerTags.TAG_LASTNAME); int objAge = jsonObj.getInt(CustomerTags.TAG_AGE); // Address JSONObject objAddress = jsonObj.getJSONObject(CustomerTags.TAG_ADDRESS); String objStreet = objAddress.getString(CustomerTags.TAG_STREET_ADDRESS); String objCity = objAddress.getString(CustomerTags.TAG_CITY); String objState = objAddress.getString(CustomerTags.TAG_STATE); String objPostalCode = objAddress.getString(CustomerTags.TAG_POSTAL_CODE); // Phone Number JSONArray arrPhone = jsonObj.getJSONArray(CustomerTags.TAG_PHONE); String[] type = new String[arrPhone.length()]; String[] number = new String[arrPhone.length()]; for (int i = 0; i < arrPhone.length(); i++){ JSONObject objPhone = arrPhone.getJSONObject(i); type[i] = objPhone.getString(CustomerTags.TAG_TYPE); number[i] = objPhone.getString(CustomerTags.TAG_NUMBER); } firstName.setText(getResources().getString(R.string.first_name, objFirstName)); lastName.setText(getResources().getString(R.string.last_name, objLastName)); age.setText(getResources().getString(R.string.age, objAge)); street.setText(getResources().getString(R.string.street, objStreet)); city.setText(getResources().getString(R.string.city, objCity)); state.setText(getResources().getString(R.string.state, objState)); postalCode.setText(getResources().getString(R.string.postal_code, objPostalCode)); home.setText(type[0] +" : "+number[0]); fax.setText(type[1] + " : "+number[1]); } catch (JSONException e) { e.printStackTrace(); } } }
Build dan jalankan maka kesannya sebagai berikut :
Source lengkap sanggup dilihat di https://github.com/andronut/Android-JSONParsing
Sekian dan supaya bermanfaat.
Happy Coding :)
Comments
Post a Comment