Android provides four different classes to manipulate
JSON data. These classes are JSONArray,JSONObject,JSONStringer and
JSONTokenizer.
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 getStringreturns 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 |
2 | getBoolean(String name) This method returns the boolean value specified by |
3 | getDouble(String name) This method returns the double value specified by the |
4 | getInt(String name) This method returns the integer value specified by |
5 | getLong(String name) This method returns the long value specified by the |
6 | length() This method returns the number of name/value mappings |
7 | names() This method returns an array containing the string |