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

}

 

태그: 
youngdeok의 이미지

Language

Get in touch with us

"어떤 것을 완전히 알려거든 그것을 다른 이에게 가르쳐라."
- Tryon Edwards -