JSON (JavaScript Object Notation):
JSON is a light weight one, which help us to interchange data in a simple manner.
JSON is built on two structures:
1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
For Instance in Java we refer it is an Object.
2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
For Instance in Java we refer it as array.
Rules for creating a JSON string:
A JSON string contains either an array of values, or an object (an associative array of name/value pairs).
An array is surrounded by square brackets, [ and ], and contains a comma-separated list of values.
An object is surrounded by curly brackets, { and }, and contains a comma-separated list of name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon (:), followed by the field value.
A value in an array or object can be:
A number (integer or floating point)
A string (in double quotes)
A boolean (true or false)
Another array (surrounded by square brackets, [ and ])
Another object (surrounded by curly brackets, { and })
The value null
Example of a JSON:
Starting point of JSON object so we used curly brackets
{" data ":
{
"Book Title": “C world",
“Book Author ": “Dennis Retchie”,
"address":
“_comment”: “another JSON Object...",
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
“_comment”: “Starting of JSON Array...",
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
} }
Let us fetch the Value from JSON in Android
Step 1: Create JSONObject as shown I below
private JSONObject myJSONObject=new JSONObject(),myJSONfetchdata;
Step 2: Initialize it as I Shown Below
myJSONfetchdata = myJSONObject.getJSONObject(“data”);
Step 3: Fetch the Values as I Shown Below
String mybooktitle = myJSONfetchdata.getString("Book Title");
String mybookauthor= myJSONfetchdata.getString("Book Author ");
JSONObject address =myJSONfetchdata. getJSONObject ("address");
String streetAddress =address.getString("streetAddress");
String city = address.getString("city");
String state = address.getString("state");
String postalCode = address.getString("postalCode");
JSONArray phoneNumber = myJSONfetchdata.getJSONArray(“phoneNumber”);
String[] type = new String[phoneNumber.length()];
String[] number = new String[phoneNumber.length()];
for(int z=0;z< phoneNumber.length();z++)
{
type [z] = phoneNumber.getString("type ");
number [z] = phoneNumber.getString("number");
}