Get Key Values of Nested JSON Objects

Question

Source: https://stackoverflow.com/questions/71136925/get-key-values-of-nested-json-objects

I want to get values of the keys of the next JSON file using org.json library:

{

"1": {

"subject1": "MIS",

"subject2": "DBMS",

"subject3": "UML"

},

"2": {

"subject1": "ART",

"subject2": "MATH",

"subject3": "MUSIC"

},

"3": {

"subject1": "HISTORY",

"subject2": "CHEMISTY",

"subject3": "BIOLOGY"

}

}

This is what I have tried:

package com.company;

import org.json.JSONArray;

import org.json.JSONObject;

import java.io.FileReader;

public class Main {

public static void main(String[] args) {

String json = "{\"1\": {\"subject1\": \"MIS\",\"subject2\": \"DBMS\",\"subject3\": \"UML\"},\"2\": {\"subject1\": \"ART\",\"subject2\": \"MATH\",\"subject3\": \"MUSIC\"},\"3\": {\"subject1\": \"HISTORY\",\"subject2\": \"CHEMISTY\",\"subject3\": \"BIOLOGY\"}}";

try{

JSONObject root = new JSONObject(json);

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

JSONArray subjects = root.getJSONArray(String.valueOf(i+1));

for (int j = 0; j < subjects.length(); j++) {

JSONObject number = subjects.getJSONObject(j);

String s1 = number.getString("subject1");

String s2 = number.getString("subject2");

String s3 = number.getString("subject3");

System.out.println(s1+","+ s2+","+s3);

}

}

}catch(Exception e){

e.printStackTrace();

}

}

}

WithJSONArray subjects = root.getJSONArray(String.valueOf(i+1));I thought I was getting:

JSONArray subjects = root.getJSONArray("1");

JSONArray subjects = root.getJSONArray("2");

...

But that doesn´t work for me. I just get in console the next:

org.json.JSONException: JSONObject["1"] is not a JSONArray.

at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2694)

at org.json.JSONObject.getJSONArray(JSONObject.java:777)

at com.company.Main.main(Main.java:18)

And I would like to get:

MIS, DBMS, UML

ART, MATH, MUSIC

HISTORI, CHEMISTRY, BIOLOGY

Can you tell me what I am doing wrong? Should I use another library? Thanks for your help.

Answer

The code will be lengthy to get data from a file of nested JSON format in Java.

You can use SPL, the open-source Java package, to get this done. It is simple and only one line of code is sufficient:

A

1

=json(file("org.json").read()).array()

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as getjsonarray.splx and invoke it in Java as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call getjsonarray()");
st.execute();

View SPL source code.