Android Json Parsing Tutorial:
JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.
To do json parsing first of all you have the need to understand the structure of json .Following diagram illustrate the basic tags which we use repeatedly according to the need.
Below is the basic jason format:
{
"contacts"
: [
{
"id"
:
"c200"
,
"name"
:
"Lucky Rana"
,
"email"
:
"luckyrana@gmail.com"
,
"address"
:
"xx-xx-xxxx,x - street, x - country"
,
"gender"
:
"male"
,
"phone"
: {
"mobile"
:
"+91 0000000000"
,
"home"
:
"00 000000"
,
"office"
:
"00 000000"
}
},
{
"id"
:
"c201"
,
"name"
:
"Johnny Depp"
,
"email"
:
"deepak chettri@gmail.com"
,
"address"
:
"xx-xx-xxxx,x - street, x - country"
,
"gender"
:
"male"
,
"phone"
: {
"mobile"
:
"+91 0000000000"
,
"home"
:
"00 000000"
,
"office"
:
"00 000000"
}
},
.
.
.
.
]
}
Writing JSON Parser Class
In your project create a class file and name it as JSONParser.java. The parser class has a method which will make http request to get JSON data and returns a JSONObject.
JSONParser.java
package
com.androidhive.jsonparsing;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.io.UnsupportedEncodingException;
import
org.apache.http.HttpEntity;
import
org.apache.http.HttpResponse;
import
org.apache.http.client.ClientProtocolException;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.impl.client.DefaultHttpClient;
import
org.json.JSONException;
import
org.json.JSONObject;
import
android.util.Log;
public
class
JSONParser {
static
InputStream is =
null
;
static
JSONObject jObj =
null
;
static
String json =
""
;
// constructor
public
JSONParser() {
}
public
JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient =
new
DefaultHttpClient();
HttpPost httpPost =
new
HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(ClientProtocolException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
try
{
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(
is,
"iso-8859-1"
),
8
);
StringBuilder sb =
new
StringBuilder();
String line =
null
;
while
((line = reader.readLine()) !=
null
) {
sb.append(line +
"\n"
);
}
is.close();
json = sb.toString();
}
catch
(Exception e) {
Log.e(
"Buffer Error"
,
"Error converting result "
+ e.toString());
}
// try parse the string to a JSON object
try
{
jObj =
new
JSONObject(json);
}
catch
(JSONException e) {
Log.e(
"JSON Parser"
,
"Error parsing data "
+ e.toString());
}
// return JSON String
return
jObj;
}
}
Json have only three data items which we use to retrieve data:
1. Json array
"contacts"
: [
{
"id"
:
"c200"
,
"name"
:
"Lucky Rana"
,
"email"
:
"luckyrana@gmail.com"
,
"address"
:
"xx-xx-xxxx,x - street, x - country"
,
"gender"
:
"male"
,
"phone"
: {
"mobile"
:
"+91 0000000000"
,
"home"
:
"00 000000"
,
"office"
:
"00 000000"
}
}]
To retrieve this "contact" array we use following syntex:
// Creating JSON Parser instance
JSONParser jParser =
new
JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try
{
// Getting Array of Contacts
contacts = json.getJSONArray("contact");
Log.d("Contact array Data",json.toString());
}
catch
(JSONException e)
{
e.printStackTrace();
}
2. Json object
"phone"
: {
"mobile"
:
"+91 0000000000"
,
"home"
:
"00 000000"
,
"office"
:
"00 000000"
}
To retrieve this "phone" object data we use following syntex:
// Creating JSON Parser instance
JSONParser jParser =
new
JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try
{
// Getting Array of Contacts
contacts = json.getJSONArray("contact");
// looping through All Contacts
for
(
int
i =
0
; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(phone);
Log.d("Phone object Data",phone.toString());
}
catch
(JSONException e)
{
e.printStackTrace();
}
3. Json string
"id"
:
"c200"
To retrieve this "phone" object data we use following syntex:
// Creating JSON Parser instance
JSONParser jParser =
new
JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try
{
// Getting Array of Contacts
contacts = json.getJSONArray("contact");
// looping through All Contacts
for
(
int
i =
0
; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String name = c.getString("name");
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(phone);
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
Log.d("String Data",mobile.toString());
}
catch
(JSONException e)
{
e.printStackTrace();
}
Example 1:
{ "contacts" : [ { "id" : "c200" , "name" : "Lucky Rana" , "email" : "luckyrana@gmail.com" , "address" : "xx-xx-xxxx,x - street, x - country" , "gender" : "male" , "phone" : { "mobile" : "+91 0000000000" , "home" : "00 000000" , "office" : "00 000000" } }, { "id" : "c201" , "name" : "Johnny Depp" , "email" : "deepak chettri@gmail.com" , "address" : "xx-xx-xxxx,x - street, x - country" , "gender" : "male" , "phone" : { "mobile" : "+91 0000000000" , "home" : "00 000000" , "office" : "00 000000" } }, . . . . ] } |
Writing JSON Parser Class
In your project create a class file and name it as JSONParser.java. The parser class has a method which will make http request to get JSON data and returns a JSONObject.
package com.androidhive.jsonparsing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null ; static JSONObject jObj = null ; static String json = "" ; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader( new InputStreamReader( is, "iso-8859-1" ), 8 ); StringBuilder sb = new StringBuilder(); String line = null ; while ((line = reader.readLine()) != null ) { sb.append(line + "\n" ); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e( "Buffer Error" , "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e( "JSON Parser" , "Error parsing data " + e.toString()); } // return JSON String return jObj; } } Json have only three data items which we use to retrieve data:
1. Json array
"contacts" : [ { "id" : "c200" , "name" : "Lucky Rana" , "email" : "luckyrana@gmail.com" , "address" : "xx-xx-xxxx,x - street, x - country" , "gender" : "male" , "phone" : { "mobile" : "+91 0000000000" , "home" : "00 000000" , "office" : "00 000000" } }]
To retrieve this "contact" array we use following syntex: // Creating JSON Parser instance JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts contacts = json.getJSONArray("contact"); } catch (JSONException e) { e.printStackTrace(); }
2. Json object
"phone" : { "mobile" : "+91 0000000000" , "home" : "00 000000" , "office" : "00 000000" } To retrieve this "phone" object data we use following syntex: JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts contacts = json.getJSONArray("contact");
// looping through All Contacts
} catch (JSONException e) { e.printStackTrace(); }
3. Json string
"id" : "c200"
To retrieve this "phone" object data we use following syntex:
// Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts contacts = json.getJSONArray("contact"); // looping through All Contacts
} catch (JSONException e) { e.printStackTrace(); } Example 1: |
Here is an example of twitter json parsing using this url:
http://search.twitter.com/search.json?q=android
I am definitely enjoying your website. You definitely have some great insight and great stories.
ReplyDeletepython training institute in chennai
python training in Bangalore
python training in pune
Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
ReplyDeleteData science training in tambaram
Data Science training in anna nagar
Data Science training in chennai
Data science training in Bangalore
Data Science training in marathahalli
Data Science training in btm
I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favourites blog site list and will be checking back soon.
ReplyDeletejava training in chennai | java training in bangalore
java training in tambaram | java training in velachery
Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
ReplyDeleteangularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
angularjs online Training
angularjs Training in marathahalli
The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training
Your topic is very nice and helpful to us … Thank you for the information you wrote.
ReplyDeleteLearn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Bangalore Training Academy provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
Big Data Analytics Training in Bangalore
Tableau Training in Bangalore
Data Science Training in Bangalore
Workday Training in Bangalore
Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.sap abap training in bangalore
ReplyDeleteI really enjoy reading and also appreciate your work..
ReplyDelete360digitmg artificial intelligence online course
Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
ReplyDeleteJava training in Chennai
Java Online training in Chennai
Java Course in Chennai
Best JAVA Training Institutes in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Training
Java Online Training
Some may stag in Interviews!!! OOPS!! More than 50% of students do this in their career. Instead, do Hadoop Training in Chennai at Infycle. Those students can easily clear this Interview session because more than 5 times at INFYCLE practicing mock-interview sessions, Hence students are Getting out of their interview fear.
ReplyDeleteThis post is so interactive and informative.keep update more information...
ReplyDeleteDigital Marketing Course in Tambaram
Digital Marketing Course in Chennai