Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Parsing JSON Using JSONObject

Published? true
FormatLanguage: WikiFormat

Problem:

Many websites provide data in JSON. Many applications require to parse JSON and provide that data in the application.

Solution:

Using inbuilt classes like JSONObject the process of parsing JSON is simplified in Android.

Discussion:

We use a method to generate JSON code for sample purposes. In a real application you would obtain the JSON from some web source. In this method we make use of a JSONObject class object to put in values and then to return the corresponding String (using toString() method). Creating an object of type JSONObject throws a JSONException, so we enclose the code in a try-catch block.

private String getJsonString() {
	JSONObject string = new JSONObject();
	try {
		string.put("name", "John Doe");
		string.put("age", new Integer(25));
		string.put("address", "75 Ninth Avenue 2nd and 4th Floors New York, NY 10011");
		string.put("phone", "8367667829");
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return string.toString();
}

We need to instantiate an object of class JSONObject that takes the JSON string as an argument. In this case, the JSON string is being obtained fromt he getJsonString method. From the jsonObject we extract the information and print it in a TextView.

try {
	String jsonString = getJsonString();
	JSONObject jsonObject = new JSONObject(jsonString);
	String name = jsonObject.getString("name"); 
	String age = jsonObject.getString("age");
	String address = jsonObject.getString("address");
	String phone = jsonObject.getString("phone");
	String jsonText=name + "\n" + age + "\n" + address + "\n" + phone;
   	json= (TextView)findViewById(R.id.json);
   	json.setText(jsonText);
} catch (JSONException e) {
	e.printStackTrace();
}

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LZDYxN2E3NTItMjE3Yy00YjE2LThjY2UtMGE2MTIyM2I0YjUx&hl=en_US.