Friday, April 5, 2013

How to use JSON in Android ?


JSON - JavaScript Object Notification.


JSON (JavaScript Object Notation) is an independent data exchange format. JSON is limited to text and numeric values. Binary values are not supported.

JSON is a subset of the JavaScript Specification (ECME-Script) and it is therefore directly supported in JavaScript.

Data structures in JSON are based on key / value pairs. The key is a string, the value can be a numerical value, a Boolean value (true or false) or an object.






An JSON object is a set of key / value pairs which starts with "{" and ends with "}".



sample example -
{
 firstName:'Rakesh',
 lastName:'Jha',
 address: {
   street:'BTM Bangalore.',
   number: '1095'
 }
} 



Lists are one or more values surrounded by [] and separated by ",".



[
{
 firstName:'Rakesh',
 lastName:'Jha',
 address: {
   street:'Bangalore.',
   number: '1095'
 }
}
,
{
 firstName:'Sumit',
 lastName:'Jha',
 address: {
   street:'New Delhi.',
   number: '190'
 }
}
] 



Basically JSON is Javascript, we can easy re-write JSON (above) example in JavaScript like -


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<script type="text/javascript">
<!--Evaluate the object and assign to variables --> 
var user = {
 firstName:'Rakesh',
 lastName:'Jha',
 address: {
   street:'Bangalore.',
   number: '1095'
 }
};
<!--Use the object--> 
alert(user.firstName + ' lives in street ' + user.address.street); 
document.writeln(user.firstName + ' ' +user.lastName);
</script>
</body>
</html> 


Now, once you understand what is JSON, how it is represented in JavaScript, lets talk about, how to use JSON in Android, what are the way to use JSON in Android.

JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.

Please note that some URIs return a JSONObject object while others return a JSONArray.





package com.kt.ws.example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ParseJSON extends Activity {
  
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String readServerData = readServerData(); try { JSONArray jsonArray = new JSONArray(readServerData); Log.i(ParseJSON .class .getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i(ParseJSON.class.getName(), jsonObject.getString("text")); } } catch (Exception e) { e.printStackTrace(); } } public String readServerData() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://192.168.1.10/EMS/student_details/DetailsStudent.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(ParseJSON .class .toString(), "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } }




To run this example assign the uses-permission to your AndroidManifest.xml for "android.permission.INTERNET".







Keyword - JSON, Android, JSON in Android, how to use JSON in Android
Source - wiki, google, vogella, stack overflow.