Android JSON Parser

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.

JSON data

{
  "person":{
  "name":"Jack",
  "age":27
  }
}

 

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();
  }
 }

}

 

Tags: 
youngdeok's picture

Language

Get in touch with us

"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -