Search code examples
javaorg.json

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


I have been searching all over, but I still cannot find a solution to my problem. If there is a post made already, please tell me so I can visit it. I have seen similar posts, but they follow a different JSON format than mine, so I wanted to see if it is possible and how it is possible to make it using the JSON format that will be introduced below.

Basically, what I am trying to do is get every element in a JSON file, and retrieve each element's key name and value. Both the key and the value are String values. Here is an example JSON of how I want my JSON code to look like:

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

I am using the org.json library, and I would like to know if this is possible, and if it is, how can I achieve it? What I tried to do originally was put the variables under an array named "Variables", but every time I tried getting that array, it gave me an error saying that JSONObject["Variables"] is not a JSONArray. Not sure if this is caused because of a problem in the JDK or because of a problem in my code. That is, of course, a thing to discuss in another thread. So far, this is what I have (FilePath is a String variable that contains the full path to the file):

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());
}

The above code should be working if the JSON looked something like this (yes, I said should because it does not work):

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

If it is possible, how would I be able to make get the key and value using the first JSON format? If not possible, then how would I do it in an alternative way? Keep in mind, the key name is never going to the same, as the key and value will be different depending on what the user wants them to be, so that is why it is important to be able to loop through every element and get both it's key and value.

Thank you for your time and effort.


Solution

  • "Variables" : { ... } is a JSONObject and not a JSONArray.

    For package 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();
    }
    

    For package 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);
    });