JSON PARSING

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

JSON Parsing

JSON
• JSON stands for JavaScript Object Notation. It is structured, light
weight, human readable and easy to parse. It’s a best alternative to
XML when our android app needs to interchange data from server.
XML parsing is very complex as compare to JSON parsing.

• JSON is shorter, quicker and easier way to interchange data from


server. JSON is great success and most of the API available support
JSON format.
Reasons for JSON Parsing in Android
• Interoperability:
• Standard Format: JSON is a standard data interchange format
supported by many languages and platforms, allowing Android apps
to easily communicate with various web services and APIs.
• Cross-Platform Communication: JSON enables Android applications
to exchange data with services written in different programming
languages (e.g., Node.js, Python, Java).
Reasons for JSON Parsing in Android
• Efficiency:
• Lightweight: JSON is more compact than XML, leading to faster data
transfer and reduced bandwidth usage, which is crucial for mobile
applications.
• Performance: Parsing JSON is generally faster and less resource-
intensive compared to other formats like XML.
Reasons for JSON Parsing in Android
• Ease of Use:
• Human-Readable: JSON’s simple, human-readable structure makes it
easier for developers to debug and maintain.
• Simple Parsing: JSON parsing libraries in Android (like org.json, Gson,
Moshi) provide simple APIs to convert JSON data into Java objects and
vice versa.
JSON CLASSES
• Android Provide us four different classes to manipulate JSON data.
These classes are
• JSONObject,
• JSONArray,
• JSONStringer
• and JSONTokenizer.
Sample JSON format:
• Below is the sample code of JSON. Its very simple JSON code which
gives us the list of users where each object contain the information
like user id, name, email, gender and different contact numbers.
JSON Elements In Android:
• In Android, JSON consist of many components. Below we define some
common components.
1. Array([): In a JSON, square bracket ([) represents a JSONArray.
JSONArray values may be any mix of JSONObjects, other JSONArrays,
Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may
not be NaNs, infinities etc.
JSON Elements In Android:

2. Objects({): In a JSON, curly bracket ({) represents a JSONObject. A JSONObject


represents the data in the form of key and value pair. JSONObject values may be any mix
of other JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or
NULL. Values may not be NaNs, infinities, or of any type not listed here.

3. key: A JSONObject contains a key that is in string format. A pair of key and value
creates a JSONObject.

4. Value: Each key has a value that could be primitive datatype(integer, float, String etc).
JSON Parsing In Android:
• Usually, JSON contain two types of nodes JSONArray and JSONObject
so while parsing we have to use the appropriate method. If JSON
starts from square bracket ([) we use getJSONArray() method and if
it start from curly bracket ({) then we should use the
getJSONObject() method. Apart from these there are some other
methods for better parsing JSON data.
JSONObjet Parsing methods:
• 1. get(String name): This method is used to get the value from
JSONObject. It returns the value of object type. We pass the String
type key and it returns the value of Object type if exists otherwise it
throws JSONException.
• 2. getBoolean(String name): This method is used to get the Boolean
value from JSONObject. We pass the String type key and it returns the
value of Boolean type if exists otherwise it throws JSONException.
• 3. getDouble(String name): This method is used to get the double
type value from JSONObject. We pass the String type key and it
returns the value in double type if exists otherwise it throws
JSONException.
• 4. getInt(String name): This method is used to get the int type value
from JSONObject. We pass the string type key and it returns the value
in int type if exists otherwise it throws JSONException.
• 5. getJSONArray(String name): This method is used to get the
JSONArray type value. We pass the String type key and it returns
JSONArray if exists otherwise it throws JSONException.
• 6. getJSONObject(String name): This method is used to get the
JSONObject type value. We pass the String type key and it returns the
JSONObject value if exists otherwise it throws JSONException.
• 7. getLong(String name): This method is used to get the long type
value from JSONObject. We pass the String type key and it returns the
value in long type if exists otherwise it throws JSONException.
8. getString(String name): This method is used to get the String type
value from JSONObject. We pass the String type key and it returns the
value in String type if exists otherwise it throws JSONException.
9. length(): This method is used to get the number of name/value
mappings in this object.
JSONArray Parsing methods:
• Below we define some important methods of JSONArray parsing which are
mainly used for parsing the data from JSONArray.
• 1. get(int index): This method is used to get the value from JSONArray. It
returns the value of object type. We pass the index and it returns the value
of object type if exist otherwise it throws JSONException.
• 2. getBoolean(int index): This method is used to get the Boolean value
from JSONArray. We pass the index and it returns the value of Boolean type
if exists otherwise it throws JSONException.
• 3. getDouble(int index): This method is used to get the double type value
from JSONArray. We pass the index and it returns the value in double type
if exists otherwise it throws JSONException.
JSONArray Parsing methods:
• 4. getInt(int index): This method is used to get the int type value from
JSONArray. We pass the index and it returns the value in int type if exists
otherwise it throws JSONException.
• 5. getJSONArray(int index): This method is used to get the JSONArray type
value. We pass the index and it returns JSONArray if exists otherwise it throws
JSONException.
• 6. getJSONObject(int index): This method is used to get the JSONObject type
value. We pass the index and it returns the JSONObject value if exists
otherwise it throws JSONException.
• 7. getLong(int index): This method is used to get the long type value from
JSONArray. We pass the index and it returns the value in long type if exists
otherwise it throws JSONException.
example code to JSONArray Parsing
methods:
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
public class JSONArrayParsingExample { public static void main(String[]
args)
{
// Sample JSON array
String jsonString = "[{\"name\": \"John\", \"age\": 30, \"isMarried\":
true}, {\"name\": \"Jane\", \"age\": 25, \"isMarried\": false}]";
output
Example of Simple JSON Parsing In Android
Studio:
• In this example we parse the data from JSON
and then display it in the UI.In this, we have
employee name and salary stored in JSON
format. Firstly we create two TextView‘s in
our XML file and then in our Activity we
parse the data using JSONObject methods
and set it in the TextView‘s.
XML CODE
//In this step we create two TextView‘s for displaying employee name
and salary.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>
XML CODE
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Name"
android:textColor="#000"
android:textSize="20sp" />

<TextView
android:id="@+id/salary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="Salary"
android:textColor="#000"
android:textSize="20sp" />
MainActivity.Java

package com.example.jsonparsing; // Package declaration

import androidx.appcompat.app.AppCompatActivity; // Import statement for AppCompatActivity


import android.os.Bundle; // Import statement for Bundle
import android.widget.TextView; // Import statement for TextView
import org.json.JSONException; // Import statement for JSONException
import org.json.JSONObject; // Import statement for JSONObject
public class MainActivity extends AppCompatActivity { // MainActivity class declaration extending AppCompatActivity

String JSON_STRING = "{\"employee\":{\"name\":\“saima yasmeen\",\"salary\":100000}}"; // JSON string with employee details


String name, salary; // Variables to hold employee name and salary
TextView employeeName, employeeSalary; // TextView variables to display employee name and salary

@Override
protected void onCreate(Bundle savedInstanceState) { // onCreate method, the entry point of the activity
super.onCreate(savedInstanceState); // Call the superclass method
setContentView(R.layout.activity_main); // Set the content view to activity_main layout
// Get the reference of TextViews from the layout
employeeName = findViewById(R.id.name); // Find the TextView for the employee name
employeeSalary = findViewById(R.id.salary); // Find the TextView for the employee salary

try {
// Get JSONObject from the JSON string
JSONObject obj = new JSONObject(JSON_STRING); // Create a JSONObject from the JSON string

// Fetch JSONObject named "employee"


JSONObject employee = obj.getJSONObject("employee"); // Get the JSONObject named "employee"

// Get employee name and salary from the JSONObject


name = employee.getString("name"); // Extract the employee name
salary = employee.getString("salary"); // Extract the employee salary

// Set employee name and salary in the TextViews


employeeName.setText("Name: " + name); // Set the name in the employeeName TextView
employeeSalary.setText("Salary: " + salary); // Set the salary in the employeeSalary TextView
}
catch (JSONException e) { // Catch any JSONException that may occur
e.printStackTrace(); // Print the stack trace for the exception
}
}
}
Stack trace
• The printStackTrace method in Java is used to print the stack trace of
a Throwable object to the standard error stream, which is typically
the console. This is useful for debugging purposes because it provides
detailed information about the exception, including the sequence of
method calls that led to the exception being thrown.
• In Java, the Throwable class is the superclass of all errors and
exceptions that can be thrown by the Java Virtual Machine (JVM) or
can be manually thrown using the throw statement. The Throwable
class is part of the Java Exception Handling mechanism and serves as
the root class for all exception and error types.

You might also like