Parsing JSON Object in ANDROID.
JSON are alternative to XML and easy to understand than XML.
As other languages Java also supports JSON parsing.
Here is a simple example of JSON parsing in ANDROID.
This is the JSON String that I am going to parse.
{"A":
{ "A1":"A1_value" ,"A2":"A2_value","sub":
{ "sub1":[ {"sub1_attr":"sub1_attr_value" }]}
}
}";
And this JSON is same as this xml.
<A A1="A1_value" A2="A2_value"> <sub> <sub1 sub1_attr="sub1_attr_value" /> </sub> <A>
Here is the code for this parsing.
package pack.coderzheaven;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JSON_Demo extends Activity {
private JSONObject jObject;
private String test = "{"A": { "A1":"A1_value" ,"A2":"A2_value", "sub": { "sub1":[ {"sub1_attr":"sub1_attr_value" }] } } }";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(test);
JSONObject menuObject = jObject.getJSONObject("A");
String attributeId1 = menuObject.getString("A1");
System.out.println("A1 value == " +attributeId1);
String attributeId2 = menuObject.getString("A2");
System.out.println("A2 value == " +attributeId2);
JSONObject popupObject = menuObject.getJSONObject("sub");
JSONArray menuitemArray = popupObject.getJSONArray("sub1");
System.out.println("sub1_attr = " + menuitemArray.getJSONObject(0).getString("sub1_attr").toString());
}
}
Please check the Logcat for the output.
Posts to come.
More complex JSON String parsing in ANDROID.
Please leave your valuable comments.
Link to this post!