Thursday, October 6, 2011

Parsing JSON Results in Android

One of the common requirements for an android programmer is how to parse incoming JSON results from another web service or application into android. JSON is a data interchange format, and serves the same purpose as that of XML. XML is slowly being replaced by JSON because it’s easy to parse, light weight, and efficient too. We had talked about SOAP vs JSON earlier and not going to go into details again.
Let us focus on how to parse JSON results in Android.
We can parse JSON by 2 methods
i)  Using JSONObject and JSONTokener classes provided by Android SDK.
ii) Using external libraries. E.g GSON, Jackson etc.
(for more details refer
Let’s consider JSON data of the form:
“name”: “myName”,
“message”: ["myMessage1","myMessage2"],
“place”: “myPlace”,
“date”:  ”thisDate”

Parsing JSON data using JSONTokener

class main extends Activity {
public void onCreate(Bundle savedInstanceState) {
try {
/* Inflate TextView from the layout */
TextView tv = (TextView)findViewById(;
/* JSON data considered as an example. Generally this data is obtained
from a web service.*/
String json = “{”
+ “  \”name\”: \”myName\”, ”
+ “  \”message\”: [\"myMessage1\",\"myMessage2\"],”
+ “  \”place\”: \”myPlace\”, ”
+ “  \”date\”: \”thisDate\” ”
+ “}”;
/* Create a JSON object and parse the required values */
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String name = object.getString(“name”);
String place = object.getString(“place”);
String date = object.getString(“date”);
JSONArray message = object.getJSONArray(“message”);
tv.setText(“Name: “+ name +”\n\n”);
tv.append(“Place: “+ place +”\n\n”);
tv.append(“Date: “+ date +”\n\n”);
for(int i=0;i<message.length();i++)
tv.append(“Message: “+ message.getString(i) +”\n\n”);
} catch (JSONException e) {e.printStackTrace();}
catch(Exception ex){ex.printStackTrace();}

No comments: