【发布时间】:2021-06-10 06:19:29
【问题描述】:
这是我的示例 json,我需要从嵌套的 json 数组中获取数据键的值,我尝试过但遇到了异常, 任何帮助表示赞赏。
{
"configurations": [
{
"data": "values",
"array": [
{
"fieldType": "count",
"datas": "countdata"
},
{
"fieldType": "welcome",
"datas": "welcomeData"
}
]
}
]
}
这是我正在尝试的示例代码,但在这里我得到了如下所示的异常,这里的限制是我们只能使用 org.json 库。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
public class TestData {
public static void matchingColumnCount(String input_file_path) throws Exception {
String contents = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObject = new JSONObject(contents);
JSONArray columnDefsDatasValue = jsonObject.getJSONArray("configurations");
ArrayList<String> arrayList = new ArrayList<String>();
for (int i = 0; i < columnDefsDatasValue.length(); i++) {
JSONArray jsonArray = columnDefsDatasValue.getJSONObject(i).getJSONArray("array");
for (int j = 0; i < jsonArray.length(); j++) {
JSONObject temp = jsonArray.getJSONObject(j);
String string = temp.getString("datas");
arrayList.add(string);
}
System.out.println("get Datas Values" + arrayList);
}
}
public static void main(String[] args) throws Exception {
String inputFileName = "test.json";
String input_file_path = "/home/Videos" + "/" + inputFileName;
matchingColumnCount(input_file_path);
}
}
例外:-
Exception in thread "main" org.json.JSONException: JSONArray[2] not found.
at org.json.JSONArray.get(JSONArray.java:194)
at org.json.JSONArray.getJSONObject(JSONArray.java:292)
at com.planlytx.TestData.matchingColumnCount(TestData.java:20)
at com.planlytx.TestData.main(TestData.java:31)
【问题讨论】: