Android JSON Parser

JSON (Javascript Object Notation) is a programming language . It is minimal, textual, and a subset of JavaScript. It is an alternative to XML. Android provides support to parse the JSON object and array.

Advantage of JSON over XML

1) JSON is faster and easier than xml for AJAX applications.
2) Unlike XML, it is shorter and quicker to read and write.
3) It uses array.

JSON Object

A JSON object contains key/value pairs like map. The keys are strings and the values are the JSON types. Keys and values are separated by comma. The { (curly brace) represents the json object.

Example
 {
    "employee":
{
        "name":       "sachin",
        "salary":      56000,
        "married":    true
 }
}

JSON Array

The [ (square bracket) represents the json array.

Example
{
"Employee" :
    [
     {"id":"101","name":"Sonoo Jaiswal","salary":"50000"},
     {"id":"102","name":"Vimal Jaiswal","salary":"60000"}
    ]
}

Android Example

JSON Object Example

Layout File

<TextView
        android:text="Json Tect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text1"/>

Activity Class


    public class MainActivity extends Activity
{
    TextView tv;
    public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":1000}}";
    @Override
    protected void onCreate(Bundle savedInstanceState)
   {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.text1);
       try
       {
         JSONObject emp = (new JSONObject(JSON_STRING)).getJSONObject("employee");
         String empname = emp.getString("name");
         int empsalary = emp.getInt("salary");
         String str = "Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
         tv.setText(str);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
   }
}

Android Example


JSON Array Example

Layout File 

<TextView
        android:text="Json Tect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text1"/>

Activity Class

public class MainActivity extends Activity
{
  TextView tv;
  public static final String strJson="{\"Employee\" :[{\"id\":\"101\",\"name\":\"Sachin\",\"salary\":\"150000\"},{\"id\":\"102\",\"name\":\"Mohan\",\"salary\":\"160000\"}] }";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.text1);
        String data = "";
        try
        {
       JSONObject jsonObject = new JSONObject(strJson);
JSONArray jsonArray= jsonObject.getJSONArray("Employee");
     for (int i=0;i<="" div="">

URL

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();
} catch (Exception e) {
    // Oops
}
finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Create a JSONObject:
JSONObject jObject = new JSONObject(result);

To get a specific string
String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long
long aJsonLong = jObject.getBoolean("LONGNAME");

To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

URL

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();
} catch (Exception e) {
    // Oops
}
finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Create a JSONObject:
JSONObject jObject = new JSONObject(result);

To get a specific string
String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long
long aJsonLong = jObject.getBoolean("LONGNAME");

To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}
 I hope you benefit from this value-in-brief tutorial.
Comment via Facebook
0 Comment via Google

0 تعليقات:

Post a Comment