articles

Home / DeveloperSection / Articles / JSON in Android

JSON in Android

Manoj Pandey3430 21-Feb-2015

In my last article, we learn about Asynctask in Android. Now we see implementation of JSON in android.

JSON stands for JavaScript Object Notation is the most popular way to serialize and transmitting data over network.

JSON is a programming language. It is minimal, textual, and a subset of JavaScript. It is an alternative to XML. 

Advantage of JSON over XML

·       JSON is faster and easier than xml.

·       It shorter and quicker to read and write.

·        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.

The [(square bracket) represents the json array.

i.e.   ["1", "2", "3", "4", "5", "6", "7"] 

Here I am creating a sample of JsonObject which help you to clear concepts of json.

1.      Create an Android project.

2.      My 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/mytextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

3. Add json array in String. In String you can easily add ‘ “ ’. You need to add ‘ \ ’ before ‘ “ ‘. i.e. String string=”\”myString”; 

{ "Student" : 
    [
     {"Id":"1001","Name":"David Warner","Age":"22"},
     {"Id":"1002","Name":"Zack","Age":"23"}
    ]
}
String _sStudent = "{ \"Student\": [{ \"Id\":\"1001\",\"Name\":\"David Warner\",\"Age\":\"22\"},{\"Id\":\"1002\",\"Name\":\"Zack\",\"Age\":\"23\"}]}";

4. Add following code in your MainActivity.class 


package com.example.androidjsonsample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;i mport android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
            // Add json array like as xml
            String _sStudent = "{ \"Student\": [{ \"Id\":\"1001\",\"Name\":\"David Warner\",\"Age\":\"22\"},{\"Id\":\"1002\",\"Name\":\"Zack\",\"Age\":\"23\"}]}";             TextView myTextView;             String data = "";             JSONObject nObject;
            @Override           protected void onCreate(Bundle savedInstanceState) {                         super.onCreate(savedInstanceState);                         setContentView(R.layout.activity_main);                         try {                                     myTextView = (TextView) findViewById(R.id.mytextview);                                   // This class can coerce values to another type when requested.                                     JSONObject jsonObject = new JSONObject(_sStudent);                                     // JSONArray contains multiple JsonObject                                     JSONArray jsonArray = jsonObject.optJSONArray("Student");                                     for (int i = 0; i < jsonArray.length(); i++) {                                               nObject = jsonArray.getJSONObject(i);                                                 // Get data from JsonObjecta and add data in String.                                                 String id = nObject.optString("Id").toString();                                                 String Name = nObject.optString("Name").toString();                                                String Age = nObject.optString("Age").toString();
                                      data += "\n Student Id-: " + id + "\n Student Name-: " + Name                                                                         + "\n Age-: " + Age + "\n";
                                    }                                     myTextView.setText(data);                         } catch (JSONException e) {                                     // TODO Auto-generated catch block
                        }
            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {                         // Inflate the menu; this adds items to the action bar if it is present.                         getMenuInflater().inflate(R.menu.main, menu);                         return true;
            }
}
   Now run your application

 

       JSON in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By