Parsing JSON from URL in Android

Android and JSON

JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.
Remember that some URI’s return a JSONObject object while others return a JSONArray. The following coding uses an URI which returns an JSONArray.

We will be using URL/Web Service:

[sourcecode language=”java”]
http://mobisys.in/quicknotify/get_departments.php?company_id=1
[/sourcecode]

We will be getting following JSON:

[sourcecode language=”java”]
[{“dept”:”Mobile”,”dept_id”:”1″},{“dept”:”Web”,”dept_id”:”2″}]
[/sourcecode]

JSON has a reputation for being somewhat hard to read. JSON objects are constructed in a key:value pair format. The object’s elements are separated by commas, and each object is contained within curly braces {}.
An array of objects is contained within square brackets ‘[]’. This is a common approach to transferring a series of rows from a database to an array of objects in which each array element corresponds to a database row, and each property of the object represents a column of data.

Sample Example

So with this tutorial we will connect to a web service that serves JSON objects/ arrays. We will also learn about how to call Json web service through HttpConnection and send the parameters through GET method of HTTP. We will display the Json array fetched from server in the ListView.

Lets create a project named as”com.mobisys.android.FirstJsonExUrl” having activity
FirstJsonExUrlActivity“.

Firstly main.xml will contain:

[sourcecode language=”xml”]