Get key values of nested json objects

 

问题

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

I want to get the values of the keys of the next json file usingorg.jsonlibrary:

{

"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 other library? Thanks for your help.

解答

从嵌套json 格式的文件中获取数据。用 Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

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

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为getjsonarray.splx,在 Java 中以存储过程的方式调用脚本文件:

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

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

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

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集