1

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.

2
  • 2
    "Variables" : { ... } is a JSONObject and not a JSONArray. Commented Apr 23, 2020 at 19:14
  • 1
    The json array use [] notation, so should look like "Variables": [ {"Variable": "hi"}, {"Variable": "Batman212369"}, {"Variable": "welcome to SO"} ] so you need to change your input or your code Commented Apr 23, 2020 at 19:15

1 Answer 1

4

"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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

@Batman212369 actually the original answer should only work for JSON.simple but not for org.json because JSONObject has no keySet() method in org.json. I add another solution so you can see them for both.
The JSON.simple one seems to be working for me even though I am using org.json.
@Stuck I tried org.json and it works fine - thanks. One question - if we need to preserve the order of the elements, what can we do as the order is not the same as the Json?
if you need order you should use a list in the JSON. Objects have no guaranteed order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.