JSON Parsing In Android
In this article, we will proceed with JSON Parsing in Android. You must be wondering how data flows between your application and the server. So, several ways are using which data flows. The most popular among them are XML(Extensible Markup Language) and JSON(JavaScript Object Notation).
JSON being lightweight and structured, is better than XML and is mainly used these days. Therefore, it becomes essential to understand the steps we need to follow to parse JSON data and get the desired information.
What is JSON?
JSON (JavaScript Object notation) is a lightweight, straightforward, and structured format to interchange data between the application and the server. JSON is used to transfer data (textual information) from server to application or vice versa. Parsing the JSON data helps us in segregating required information from the JSON data.
Structure of JSON:
JSON has a structured format that makes developers easily understand and parse it. JSON can start with any of the following brackets:
- [ ] – The square brackets are used to define a JSON Array.
- { } – The curly brackets are used to denote a JSON Object.
JSON can have the following structures:
1. JSON Object – As discussed before, JSON object starts and ends with curly brackets. JSON Objects consist of several key-value pairs, JSON Arrays, and even other JSON Objects.
Below is an example of a JSON Object.
{ "Name": "TechVidvan", "Author": “Mohit Kumar”, "Languages": [“C++”, “Java”, “Kotlin”, “Dart”, “Python”, “GO”, “JavaScript”] “Frameworks”: { “Python”: [“Django”, “Flask”], “JavaScript”: [“React”, “Ionic”, “Angular”] } }
2. JSON Array – JSON Array starts and ends with square brackets consisting of a list of several values. These values can be of any type String, Integer, Float, or Boolean. Sometimes these values can also be JSON objects.
Below is an example showing a list of coding platforms in the form of a JSON Array.
[“CodeChef”, “CodeForces”, “AtCoder”, “TopCoder”, “HackerRank”]
Features of JSON
JSON provides several features which make it most widely used among developers. Some of the features of JSON are as follows:
- It is text-based and easy to understand
- It is language-independent, and no matter which language you use, you can use JSON to exchange data between your application and server
- JSON is lightweight and structured
- It is scalable
- It allows you to interchange data between application and server
- JSON can carry many types of data
JSON DataTypes
JSON currently allows six types of data which are as follows:
1. String – Using JSON, you can easily exchange String constants. Strings are a sequence of characters that is usually enclosed within double quotes(“ ”).
2. Numbers – Using JSON, you can exchange numbers(both integers and floating points).
3. Boolean – Using JSON, you can exchange Boolean data also, which includes either True or False.
4. Null – Sometimes, you may need to define a key or object as empty. In such circumstances, you can mark that object as null.
5. Object – JSON can contain several JSON objects inside it.
6. Array – JSON can contain several JSON arrays inside it.
Now, the question arises okay, we can handle strings, numbers, booleans, and other textual data, but what happens to the graphical data? How can we handle graphical data using JSON?
Now the answer is quite simple, and if your graphical asset is stored in the server, you can provide the URL as a string in the JSON and exchange data. Suppose you have an image and don’t have its URL, then you can convert it to Base64 format and then send it as a string.
Why JSON over XML in Android?
JSON and XML, as we know, are methods to exchange data, but these days JSON has the upper hand compared to XML. Let’s see the points which make JSON more feasible and a better choice than XML.
- JSON is much easier to understand and has a high performance
- JSON allows us to use arrays
- JSON structures are easy to read, write and parse
- JSON is language independent and doesn’t involve tags
- Fetching information using JSON is easy and quick compared to XML
- JSON is lightweight compared to XML
- JSON comes up with many open source libraries which help serialization and deserialization easy
- JSON supports several Ajax and backend tools
Examples of XML and JSON
Below is an example of XML:
<?xml version="1.0" encoding="UTF-8" ?> <root> <students> <name>Mohit</name> <college>SRM University AP</college> </students> <students> <name>Rahul</name> <college>IIT Bombay</college> </students> <students> <name>Sahithi</name> <college>PES University</college> </students> </root>
Below is an example of JSON:
{ "students": [ { "name": "Mohit", "college": "SRM University AP" }, { "name": "Rahul", "college": "IIT Bombay" }, { "name": "Sahithi", "college": "PES University" } ] }
JSON Parsing Functions in Android
Several functions help us to parse and take out the required information from the JSON data provided.
Method Name | Description |
getString(name: String) | The getString() method returns the string value corresponding to the key name provided in the parameter. |
getInt(name: String) | The getInt() method returns the integer value corresponding to the key name provided in the parameter. |
getBoolean(name: String) | The getBoolean() method returns the boolean value corresponding to the key name provided in the parameter. |
getDouble(name: String) | The getDouble() method returns the double value corresponding to the key name provided in the parameter. |
getJSONArray(name: String) | The getJSONArray() method returns the JSON Array corresponding to the key name provided in the parameter. |
getJSONObject(name: String) | The getJSONObject() method returns the JSON Object corresponding to the key name provided in the parameter. |
optString(name: String?) | The optString() method returns the string value corresponding to the key name provided in the parameter. If no value is present or if the key fails to match, then it returns null. |
get(index: Int) | The get() method takes an index as a parameter and returns the object present at that index in the JSON Array. |
length() | The length() method displays the number of key/value pairs present in a JSON object. It also returns the number of elements present in a JSON Array. |
Implementation of JSON Parsing in Android
JSON Parsing is quite simple and easy to understand. Below are the steps which will help you in creating an android application involving JSON Parsing. Here we will try to parse the student’s JSON data and display it in a RecyclerView.
Following is the JSON data which we will parse:
{ "students": [ { "name": "Mohit" }, { "name": "Rahul" }, { "name": "Sahithi" }, { "name": "Pramey" }, { "name": "Nitesh" }, { "name": "Gowtham" } ] }
Step 1: Start your Android Studio and click on Create New Project. Name it as TechVidvanJSON.
Step 2: Now open your activity_main.xml file and paste the below code there.
Code: activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="20dp" android:gravity="center" android:text="Tech Vidvan" android:textColor="#FF9800" android:textSize="40sp" android:textStyle="bold" /> <ListView android:id="@+id/studentsList" android:padding="10dp" android:layout_margin="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
Step 3: Lastly, come back to your MainActivity.kt file and paste the below code there.
Code: MainActivity.kt
package com.techvidvan.techvidvanjson import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.* import org.json.JSONException import org.json.JSONObject class MainActivity : AppCompatActivity() { lateinit var arrayAdapter: ArrayAdapter<*> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //binding the ListView with the variable val listview: ListView = findViewById(R.id.studentsList) //fetching the JSON data in form of string val json_stu: String = getRawJSON() try { var name_list = ArrayList<String>() //converting the raw json to JSON Object val jsObj = JSONObject(json_stu) //fetching the students JSON Array val jsArray = jsObj.getJSONArray("students") for (i in 0 until jsArray.length()) { val obj = jsArray.getJSONObject(i) //adding names of the students in the name_list name_list.add(obj.getString("name")) } //creating the array adapter object arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, name_list) //providing the array adapter to the list view listview.adapter = arrayAdapter } catch (ex: JSONException) { Log.e("JsonParser ", "Exception", ex) } } private fun getRawJSON(): String { return "{\n" + " \"students\": [\n" + " {\n" + " \"name\": \"Mohit\"\n" + " },\n" + " {\n" + " \"name\": \"Rahul\"\n" + " },\n" + " {\n" + " \"name\": \"Sahithi\"\n" + " },\n" + " {\n" + " \"name\": \"Pramey\"\n" + " },\n" + " {\n" + " \"name\": \"Nitesh\"\n" + " },\n" + " {\n" + " \"name\": \"Gowtham\"\n" + " }\n" + " ]\n" + "}" } }
Now, you are ready to test your application on your device or emulator. You may notice that the data provided was in JSON format, but we can parse it in a list form.
Summary
Through this article, you came across another essential topic known as JSON Parsing. You came across what JSON is and the structure it has. Later on, you saw its features and the type of data it can handle. You saw the difference between XML and JSON and understood why JSON is used over XML. Finally, you saw several methods that help in parsing and saw an implementation of the same.