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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...