Tutorial

Android JSONObject - JSON Parsing in Android

Published on August 4, 2022
author

Anupam Chugh

Android JSONObject - JSON Parsing in Android

Android JSONObject is used for JSON parsing in android apps. In this tutorial we’ll discuss and implement a JSONObject in our android application to parse JSON data. JSON stands for JavaScript Object Notation.

What is JSON?

JSON is used for data interchange (posting and retrieving) from the server. Hence knowing the syntax and it’s usability is important. JSON is the best alternative for XML and its more readable by human. JSON is language independent. Because of language in-dependency we can program JSON in any language (Java/C/C++). A JSON response from the server consists of many fields. An example JSON response/data is given below. We’ll use it as a reference and implement it in our application.

{
  "title":"JSONParserTutorial",
  "array":[
    {
    "company":"Google"
    },
    {
      "company":"Facebook"
    },
    {
    "company":"LinkedIn"
    },
    {
      "company" : "Microsoft"
    },
    {
      "company": "Apple"
    }
    ],
    "nested":{
    "flag": true,
    "random_number":1
    }
}

We’ve create a random JSON data string from this page. It’s handy for editing JSON data. A JSON data consists of 4 major components that are listed below:

  1. Array: A JSONArray is enclosed in square brackets ([). It contains a set of objects
  2. Object: Data enclosed in curly brackets ({) is a single JSONObject. Nested JSONObjects are possible and are very commonly used
  3. Keys: Every JSONObject has a key string that’s contains certain value
  4. Value: Every key has a single value that can be of any type string, double, integer, boolean etc

Android JSONObject

We’ll create a JSONObject from the static JSON data string given above and display the JSONArray in a ListView. We’ll change the application name to the title string in the JSON data.

JSON Parsing in Android Example

Below image shows the android studio project for json parsing example. The project consists of the default activity and layout (with a ListView). json parsing in android, android JSONObject

Android JSON Parsing Code

The activity_main.xml is given below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.jsonparsing.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:id="@+id/list_view"
        android:layout_height="match_parent"/>

</RelativeLayout>

The MainActivity.java is given below.

package com.journaldev.jsonparsing;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    String json_string = "{\n" +
            "  \"title\":\"JSONParserTutorial\",\n" +
            "  \"array\":[\n" +
            "    {\n" +
            "    \"company\":\"Google\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"company\":\"Facebook\"\n" +
            "    },\n" +
            "    {\n" +
            "    \"company\":\"LinkedIn\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"company\" : \"Microsoft\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"company\": \"Apple\"\n" +
            "    }\n" +
            "    ],\n" +
            "    \"nested\":{\n" +
            "    \"flag\": true,\n" +
            "    \"random_number\":1\n" +
            "    }\n" +
            "}";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {

            ListView listView = (ListView) findViewById(R.id.list_view);
            
            List<String> items = new ArrayList<>();
            JSONObject root = new JSONObject(json_string);

            JSONArray array= root.getJSONArray("array");

            this.setTitle(root.getString("title"));

            for(int i=0;i<array.length();i++)
            {
                JSONObject object= array.getJSONObject(i);
                items.add(object.getString("company"));
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, items);

            if (listView != null) {
                listView.setAdapter(adapter);
            }

            JSONObject nested= root.getJSONObject("nested");
            Log.d("TAG","flag value "+nested.getBoolean("flag"));

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

We’ve iterated through the JSONArray object and fetched the strings present in each child JSONObject and added them to a ArrayList that’s displayed in the ListView. The application name is changed using :

this.setTitle();

Android JSONObject Example Output

The output of the application is given below. You can see the title name changed in the ToolBar at the top. Android JSONObject, JSON Parsing in android app Google has released a Volley Library for JSON Parsing. We’ll implement that in later tutorials. GSON is a Java library that converts Java Objects into JSON and vice versa. This brings an end to android JSONObject tutorial. Our aim was to give a overview of JSON Parsing in android since JSON is the accepted standard these days for transmitting data between servers/web applications. Android JSON parsing will be very handy when we develop applications that send and receive data from the server. You can download the Android JSON Parsing Project from the below link.

Download Android JSON Parsing JSONObject Project

Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 4, 2021

how to retrive data from database table using JSON parser library

- zig girma

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 25, 2021

    how to parse this type of data::: { “status”: true, “msg”: “Main type found successfully.”, “data”: [ { “id”: 8, “name”: “Music”, “created_at”: “2020-12-11T11:14:12.000000Z”, “updated_at”: “2020-11-07T05:28:30.000000Z”, “images”: [ { “id”: 6, “category_id”: 8, “aws_s3_key”: “category/c9f0f895fb98ab9159f51fd0297e236d/160474961147830.jpg”, “media_url”: “https://ehs-media-development.s3.ap-south-1.amazonaws.com/category/c9f0f895fb98ab9159f51fd0297e236d/160474961147830.jpg”, “created_at”: “2020-11-07T06:16:53.000000Z”, “updated_at”: “2020-11-07T06:16:53.000000Z” } ] }, { “id”: 9, “name”: “Art”, “created_at”: “2020-12-11T11:14:21.000000Z”, “updated_at”: “2020-12-08T05:02:53.000000Z”, “images”: [ { “id”: 7, “category_id”: 9, “aws_s3_key”: “category/c9f0f895fb98ab9159f51fd0297e236d/160474961147830.jpg”, “media_url”: “https://ehs-media-development.s3.ap-south-1.amazonaws.com/teacher\_portfolio\_image/e4da3b7fbbce2345d7772b0674a318d5/160766398952238.jpg”, “created_at”: “2020-12-11T11:16:26.000000Z”, “updated_at”: “2020-11-07T06:16:53.000000Z” } ] } ] }

    - Devendra Aparnathi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 20, 2019

      How to get value for radio Button in json through two value jobseeker & jobprovider plz help me

      - Dhara Dadhaniya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 21, 2018

        json parsing of object or array of only numbers i try to find it everywhere not a single solution as take it as a challenge and pls help me.

        - keshav

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 17, 2018

          Hi, can you please tell me how would you parse this JSON in Android Studio" { “Article”:[ { “InvDepartmentId”:“001000000000012”, “InvDepartmentName”:“mens”, “InvCategoryId”:“001000000000023”, “InvCategoryName”:“adult”, “InvSubCategoryId”:“001000000000021”, “InvSubCategoryName”:“abc”, “ArticleId”:“001000000000186”, “ArticleNo”:“test22246”, “ArticleWSP”:1100.00, “CreatedOn”:“2018-09-14T12:51:04”, “LastUpdate”:“2018-09-14T12:51:30.823” } I have written this code until now: StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() { @Override public void onResponse(String response) { try { JSONObject js = new JSONObject(response); JSONArray jsonArray = js.getJSONArray(Constants.Article); String InvDepartmentId = jsonArray.getString(Integer.parseInt(“InvDepartmentId”)); String InvDepartmentName = jsonArray.getString(Integer.parseInt(“InvDepartmentName”)); String InvCategoryId = jsonArray.getString(Integer.parseInt(“InvCategoryId”)); Help would be highly appreciated.Thanks !

          - Akansha Rattan

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 5, 2018

            Simple and to the point, Helpful article.

            - basic

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 16, 2017

              I really love ur all tutorials, But sorry to say this1 is not that upto the mark. You could have shown it with how to get json data from url…using HTTPHandler Also asynctask can be used in this. If possible can you update your this tutorial accordingly. (Just a suggestion) Thanks

              - khushbu

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 13, 2017

                Woow man…Your teaching style is so cool…I am totally impressed…Carry on… Thank You…

                - shihab

                  Try DigitalOcean for free

                  Click below to sign up and get $200 of credit to try our products over 60 days!

                  Sign up

                  Join the Tech Talk
                  Success! Thank you! Please check your email for further details.

                  Please complete your information!

                  Become a contributor for community

                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                  DigitalOcean Documentation

                  Full documentation for every DigitalOcean product.

                  Resources for startups and SMBs

                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                  Get our newsletter

                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                  New accounts only. By submitting your email you agree to our Privacy Policy

                  The developer cloud

                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                  Get started for free

                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                  *This promotional offer applies to new accounts only.