Parsing JSON in ANDROID

JSON adalah alternatif dan mudah dimengerti dibandingkan dengan XML. Kita menggunakan String JSON utntuk respon dari web server dan menggubah dari String JSON menjadi objek array, array objek dan nilai nilai lainya dan di respon dalam bentuk TextView ataupun ListView. Disini gw bakal kasih contoh gmna kita bisa parsing dengan mengunakan “JSONObject” dan “JSONArray” untuk merespon sebuah String. JSON

{"FirstObject": { "attr1":"one value" ,"attr2":"two value" ,"attr3":"three value",
   "sub": { "sub1":[ {"sub1_attr":"sub1_attr_value" },{"sub1_attr":
   "sub2_attr_value" },{"sub1_attr":"sub3_attr_value" }]}
  }
"};

Java class

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class StartJson extends Activity {

	TextView txtParsing ;
	private JSONObject jsonObject ;

	String strParseValue = null ;
	private String strJsonValue = "{\"FirstObject\":{\"attr1\":\"One value\" ,\"attr2\":\"two value\",\"attr3\":\"three value\","
			+"\"sub\": { \"sub1\" :[{\"sub1_attr\":\"sub1_atrr_value\"},{\"sub1_attr\":\"sub2_atrr_value\"},{\"sub1_attr\":\"sub3_atrr_value\"}]}}}";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_json);

		txtParsing = (TextView)findViewById(R.id.txt_json);
		try {
			parseJSON();
		} catch (Exception e) {

		}

	}

	public void parseJSON() throws JSONException
	{
		jsonObject = new JSONObject(strJsonValue);

		JSONObject object = jsonObject.getJSONObject("FirstObject");
		String attr1 = object.getString("attr1");
		String attr2 = object.getString("attr2");
		String attr3 = object.getString("attr3");

		strParseValue ="Atribut 1 value : -> "+attr1;
		strParseValue +="\nAtribut 2 value : -> "+attr2;
		strParseValue +="\nAtribut 3 value : -> "+attr3;

		JSONObject subObject = object.getJSONObject("sub");
		JSONArray subArray = subObject.getJSONArray("sub1");

		strParseValue+="\n \n array length -> "+subArray.length();	   	

		for(int i=0;i<subArray.length() ; i++)
		{
			strParseValue+="\n \n "+subArray.getJSONObject(i).getString("sub1_attr").toString();
		}

		txtParsing.setText(strParseValue);

	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s