如何使用 org.json 库从 Java 中的 JSON 文件获取每个键和值?

How can I get every key and value from a JSON file in Java using the org.json library?

我到处寻找,但仍然找不到解决问题的办法。如果已经制作了 post,请告诉我,以便我访问它。我见过类似的 posts,但它们遵循与我不同的 JSON 格式,所以我想看看是否可能以及如何使用 JSON 格式下面会介绍。

基本上,我要做的是获取 JSON 文件中的每个元素,并检索每个元素的键名和值。键和值都是字符串值。这是我希望我的 JSON 代码的示例 JSON:

{
  "Variable1":"-",
  "Variable2":" Test "
}

我正在使用 org.json 库,我想知道这是否可行,如果可行,我该如何实现?我最初尝试做的是将变量放在名为 "Variables" 的数组下,但每次我尝试获取该数组时,它都会给我一个错误,提示 JSONObject["Variables"] 是不是 JSON 数组。不确定这是由于 JDK 中的问题还是我的代码中的问题引起的。当然,这是要在另一个线程中讨论的事情。到目前为止,这就是我所拥有的(FilePath 是一个包含文件完整路径的字符串变量):

String Contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject JsonFile = new JSONObject(Contents);
JSONArray VariableList = JsonFile.getJSONArray("Variables");
for (Object Item: VariableList) {
    Map.Entry Item2 = (Map.Entry)Item;
    System.out.println("Key: " + Item2.getKey() + ", Value: " + Item2.getValue());
}

如果 JSON 看起来像这样,上面的代码应该可以工作(是的,我说应该是因为它不起作用):

{
  "Variables": {
    "Variable1":"-",
    "Variable2":" Test "
  }
}

如果可能的话,我怎样才能使用第一种 JSON 格式获取键和值?如果不可能,那么我将如何以其他方式进行?请记住,键名永远不会相同,因为键和值会根据用户希望的不同而不同,因此这就是为什么能够遍历每个元素并同时获得两者的重要性这是关键和价值。

感谢您的时间和精力。

"Variables" : { ... }JSONObject 而不是 JSONArray

包裹org.json

try {
    String contents = "{\"Variables\":{\"Variable1\":\"-\",\"Variable2\":\" Test \"}}";
    JSONObject jsonFile = new JSONObject(contents);
    JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
    JSONArray keys = variableList.names ();
    for (int i = 0; i < keys.length (); ++i) {
        String key = keys.getString(i);
        String value = variableList.getString(key);
        System.out.println("key: " + key + " value: " + value);
    }
} catch (Exception e) {
    e.printStackTrace();
}

包裹JSON.simple

String contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject jsonFile = new JSONObject(contents);
JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
variableList.keySet().forEach(key -> {
    Object value = jsonObj.get(key);
    System.out.println("key: "+ key + ", value: " + value);
});