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 are interested in getting temperature only.
{
“sys”:
{
“country”:”GB”,
“sunrise”:1381107633,
“sunset”:1381149604
},
“weather”:[
{
“id”:711,
“main”:”Smoke”,
“description”:”smoke”,
“icon”:”50n”
}
],
“main”:
{
“temp”:304.15,
“pressure”:1009,
}
}
JSON – Elements
A JSON file consists 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 | KeyA JSON object contains a key that is just a string. Pairs of key/value make up a JSON object |
4 | ValueEach 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. A JSON file consists of different objects with different key/value pairs e.t.c. So JSONObject has a separate function for parsing each of the components of a 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 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. |