Android - JSON Parser Tutorial

Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer
and JSONTokenizer.

{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}

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

上一篇:Java包名命名规则(转载)


下一篇:Maven构建war项目添加版本号