7/30/2015 5:48:28 AM
Viewed: 1610
2/5/2013 4:59:47 PM
Android - JSON Parser Tutorial

Android - JSON Parser Tutorial

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.

Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.


JSON - Elements

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −

Sr.No Component & description
1 Array([)

In a JSON file , square bracket ([) represents a JSON array

2 Objects({)

In a JSON file, curly bracket ({) represents a JSON object

3 Key

A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object

4 Value

Each key has a value that could be string , integer or double e.t.c

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:

String in;
JSONObject reader = new JSONObject(in);

The last step is to parse the JSON. An JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below:

JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");

The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.

Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These methods are listed below −

Sr.No Method & description
1 get(String name)

This method just Returns the value but in the form of Object type

2 getBoolean(String name)

This method returns the boolean value specified by the key

3 getDouble(String name)

This method returns the double value specified by the key

4 getInt(String name)

This method returns the integer value specified by the key

5 getLong(String name)

This method returns the long value specified by the key

6 length()

This method returns the number of name/value mappings in this object..

7 names()

This method returns an array containing the string names in this object.


To experiment with this example , you can run this on an actual device or in an emulator.

Steps Description
1 You will use Android studio to create an Android application. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add necessary code.
3 Modify the res/layout/activity_main to add respective XML components
4 Modify the res/values/string.xml to add necessary string components
5 Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modified main activity file src/MainActivity.java.

package com.tutorialspoint.json;

import android.app.Activity;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

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.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      TextView output = (TextView) findViewById(R.id.textView1);
      String strJson="
         \"Employee\" :[
            \"name\":\"Gopal Varma\",
            \"name\":\"Sathish kallakuri\",
      String data = "";
      try {
         JSONObject  jsonRootObject = new JSONObject(strJson);
         //Get the instance of JSONArray that contains JSONObjects
         JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
         //Iterate the jsonArray and print the info of JSONObjects
         for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());
            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
      } catch (JSONException e) {e.printStackTrace();}

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
      android:text="JSON example"
      android:textSize="30dp" />
      android:text="Tutorials Point"
      android:textColor="#ff16ff01" />
      android:text="New Text"
      android:layout_alignParentEnd="true" />

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <uses-permission android:name="android.permission.INTERNET"/>
      android:theme="@style/AppTheme" >
         android:label="@string/app_name" >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Anroid XML Parser Tutorial

Above Example showing the data from string json,The data has contained employer details as well as salary information

Gửi trả lời