Skip to main content

How to convert JSONObject and JSONArray into Java List | JSONArray and JSONObject

Convert JSON Object data into Java List and Display accordingly | Convert String JSONObject and JSONArray data into List in Java

Convert JSON Object and JSONarray into Java List

Often times we need to call Third party API and we get JSON response, and want to display data into web page. Sometimes we got complex JSON response and difficult to convert into Java data structure.

First learn how to call third party rest API in Java.

So lets see how we can easily convert JSON data into our Java data structure. Following sample JSON data.

{
"ProgrammingList": [
{
"id": "1",
"name": "Java",
"edition": "third"
},
{
"id": "2",
"name": "Python",
"edition": "fourth"
},
{
"id": "3",
"name": "JavaScript",
"edition": "Fifth"
},
{
"id": "4",
"name": "c#",
"edition": "second"
}
],

}

For below example you must need org.json library. For that you can do following things.

  1. Create Web Dynamic Project in Eclipse and add "java-json.jar" into WebContent -> WEB-INF -> lib folder.
  2. Create maven project and add following dependency in pom.xml file
 <!-- https://mvnrepository.com/artifact/org.json/json -->
 <dependency>
     <groupId>org.json</groupId>
     <artifactId>json</artifactId>
     <version>20210307</version>
 </dependency>

Example 1 : Convert and display JSON String Object into Java ArrayList

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class ConvertJsonObjectToList {

    public static void main(String[] args) {
        try {
            convertJsonToList();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void convertJsonToList() throws JSONException {
       
        // JSON data in string
        String programmingData = "{\r\n"
                + "  \"ProgrammingList\": [\r\n"
                + "    {\r\n"
                + "      \"id\": \"1\",\r\n"
                + "      \"name\": \"Java\",\r\n"
                + "      \"edition\": \"third\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"2\",\r\n"
                + "      \"name\": \"Python\",\r\n"
                + "      \"edition\": \"fourth\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"3\",\r\n"
                + "      \"name\": \"JavaScript\",\r\n"
                + "      \"edition\": \"Fifth\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"4\",\r\n"
                + "      \"name\": \"c#\",\r\n"
                + "      \"edition\": \"second\"\r\n"
                + "    }\r\n"
                + "  ],\r\n"
                + "  \r\n"
                + "}";
       
        // Get 'ProgrammingList' Object data into string
        String objectData = new JSONObject(programmingData).get("ProgrammingList").toString();

        // creating JSONArray of string objectData
        JSONArray jsonArray = new JSONArray(objectData);;
    
        List<Map<String,String>> listOfAllData = new ArrayList<>();

        // Traverse through jsonArray and put data into map of list
        for(int index = 0; index < jsonArray.length(); index++) {
           
            Map<String,String> mapOfEachData = new HashMap<>();
            JSONObject eachObject = new JSONObject(jsonArray.get(index).toString());
            mapOfEachData.put("id", eachObject.get("id").toString());
            mapOfEachData.put("name", eachObject.getString("name").toString());
            mapOfEachData.put("edition", eachObject.getString("edition").toString());
            listOfAllData.add(mapOfEachData);
        }   
       
        // Print All Json data
        for (Map<String, String> entry : listOfAllData) {
            System.out.print("Id : " + entry.get("id") + ", Programming Language : "
                    +entry.get("name") + ", Edition : "
                    +entry.get("edition") +"\n");
        }
    }

}

Output :

Id : 1, Programming Language : Java, Edition : third
Id : 2, Programming Language : Python, Edition : fourth
Id : 3, Programming Language : JavaScript, Edition : Fifth
Id : 4, Programming Language : c#, Edition : second

Explanation :

  • Getting "ProgrammingList" JSONObject into String objectData.
  • Creating new JSONArray of String objectData.
  • Traverse through jsonArray. (here we have 4 objects in jsonArray).
  • Getting one by one JSONObject and put in Map with String name as key and String data as value.
  • Add map into list of map after creating map of given data.
  • Print all list of map data one by one.

 

Lets see another example. following the JSON structure.

{
  "StudentList": {
    "students": [
      {
        "student_id" : "1",
        "student_name" : "student_one"
        "subjects_mark": [
          {
            "subject": "java",
            "mark": "80",
          },
          {
            "subject": "python",
            "mark": 50,
          }
        ],
      },
      {
        "student_id" : "2",
        "student_name" : "student_two"
        "subjects_mark": [
          {
            "subject": "java",
            "mark": "50",
          },
          {
            "subject": "python",
            "mark": 60,
          }
        ],
      },
      {
        "student_id" : "3",
        "student_name" : "student_three"
        "subjects_mark": [
          {
            "subject": "java",
            "mark": "75",
          },
          {
            "subject": "python",
            "mark": 80,
          }
        ],
      },
      {
        "student_id" : "4",
        "student_name" : "student_four"
        "subjects_mark": [
          {
            "subject": "java",
            "mark": "55",
          },
          {
            "subject": "python",
            "mark": 65,
          }
        ],
      }
}

Example 2 : Convert List of JSON Object to Java Map of List

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class ConvertJsonDemo {

    public static void main(String[] args) {

        try {
            onvertJsonToList();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void onvertJsonToList() throws JSONException {

        String studentsData = "{\r\n"
                + "  \"StudentList\": {\r\n"
                + "    \"students\": [\r\n"
                + "      {\r\n"
                + "        \"student_id\": \"1\",\r\n"
                + "        \"student_name\": \"student_one\",\r\n"
                + "        \"subjects_mark\": [\r\n"
                + "          {\r\n"
                + "            \"subject\": \"java\",\r\n"
                + "            \"mark\": \"80\"\r\n"
                + "          },\r\n"
                + "          {\r\n"
                + "            \"subject\": \"python\",\r\n"
                + "            \"mark\": \"50\"\r\n"
                + "          }\r\n"
                + "        ]\r\n"
                + "      },\r\n"
                + "      {\r\n"
                + "        \"student_id\": \"2\",\r\n"
                + "        \"student_name\": \"student_two\",\r\n"
                + "        \"subjects_mark\": [\r\n"
                + "          {\r\n"
                + "            \"subject\": \"java\",\r\n"
                + "            \"mark\": \"70\"\r\n"
                + "          },\r\n"
                + "          {\r\n"
                + "            \"subject\": \"python\",\r\n"
                + "            \"mark\": \"60\"\r\n"
                + "          }\r\n"
                + "        ]\r\n"
                + "      },\r\n"
                + "      {\r\n"
                + "        \"student_id\": \"3\",\r\n"
                + "        \"student_name\": \"student_three\",\r\n"
                + "        \"subjects_mark\": [\r\n"
                + "          {\r\n"
                + "            \"subject\": \"java\",\r\n"
                + "            \"mark\": \"85\"\r\n"
                + "          },\r\n"
                + "          {\r\n"
                + "            \"subject\": \"python\",\r\n"
                + "            \"mark\": \"75\"\r\n"
                + "          }\r\n"
                + "        ]\r\n"
                + "      },\r\n"
                + "      {\r\n"
                + "        \"student_id\": \"4\",\r\n"
                + "        \"student_name\": \"student_four\",\r\n"
                + "        \"subjects_mark\": [\r\n"
                + "          {\r\n"
                + "            \"subject\": \"java\",\r\n"
                + "            \"mark\": \"65\"\r\n"
                + "          },\r\n"
                + "          {\r\n"
                + "            \"subject\": \"python\",\r\n"
                + "            \"mark\": \"55\"\r\n"
                + "          }\r\n"
                + "        ]\r\n"
                + "      }\r\n"
                + "    ]\r\n"
                + "  }\r\n"
                + "}\r\n"
                + "";

        String objectData = new JSONObject(studentsData).get("StudentList").toString();
        JSONArray studentsJsonArray = new JSONArray(
            new JSONObject(objectData).get("students").toString());

        List<Map<String, String>> listOfAllData = new ArrayList<>();

        for (int i = 0; i < studentsJsonArray.length(); i++) {

            Map<String, String> mapOfEachData = new HashMap<>();
            String data = studentsJsonArray.get(i).toString();
            
            JSONObject eachStudentObj = new JSONObject(data);
            
            String studentName = eachStudentObj.get("student_name").toString();
            
            mapOfEachData.put("name", studentName);

            JSONArray marksArray = new JSONArray(
                    new JSONObject(data).get("subjects_mark").toString());
           
        for (int j = 0; j < marksArray.length(); j++) {
                String eachSubjectMark = marksArray.get(j).toString();
                JSONObject eachBOObjectMarkObj = new JSONObject(eachSubjectMark);
                mapOfEachData.put(eachBOObjectMarkObj.getString("subject"),
                        eachBOObjectMarkObj.getString("mark"));
            }

            listOfAllData.add(mapOfEachData);
        }

        for (Map<String, String> entry : listOfAllData) {
            System.out.println(entry);
        }

    }

}

Output :

{python=50, java=80, name=student_one}
{python=60, java=70, name=student_two}
{python=75, java=85, name=student_three}
{python=55, java=65, name=student_four}

 Explanation :

  • Get "StudentList" JSON Object as String format.
  • After store students JSON Object into JSONArray.
  • Traverse through studentsJsonArray.
  • Get each String student object into JSONObject. Get student name and putted in map.
  • After we also have subjects_mark JSONArray in students Object.
  • Loop through subject_mark JSONArray and putted subject name and marks in listOfAllData.
  • Last, print all list of map data one by one.
 
Happy Coding.
 
Other articles you may be like :

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last