Showing posts with label dom parser. Show all posts
Showing posts with label dom parser. Show all posts

Android JSON Parser Example



In this example we will see how to parse a JavaScript Object Notation(JSON) response. Here we will use a set of classes from the org.json package offered in Android SDK by simply creating new JSONObject from the formatted string data.

Let us parse the following JSON response:

JSON response:
{
“person”:{
“name”:“Jack”,
“age”:27
}
}
1.Create a new project File ->New -> Project ->Android ->Android Application Project. Follow the wizard to create a project. After the project is created in the layout file activity_main.xml (in my case) create two text views and give the id as name and age. Refer the below code.

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="110dp"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

2.Now in the corresponding java file MainActivity.java (in my case) we will put the JSON response in a string and parse it. Since JSON parser is strict by default , meaning the execution will halt with an exception if an invalid JSON data is found or no data is found.

MainActivity.java:
import org.json.JSONException;
import org.json.JSONObject;

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

public class MainActivity extends Activity {

 public static final String JSON_STRING = "{\"person\":{\"name\":\"Jack Sparrow\",\"age\":27}}";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  TextView name = (TextView) findViewById(R.id.name);
  TextView age = (TextView) findViewById(R.id.age);
  try {
   JSONObject person = (new JSONObject(JSON_STRING))
     .getJSONObject("person");
   String Name = person.getString("name");
   int Age = person.getInt("age");
   name.setText("Whats the name?\n" + Name);
   age.setText("Whats the age?\n" + Age);
  } catch (JSONException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
3.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows: