title: How can I get every key and value from a JSON file in Java using the org.json library?
body: <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>{
    "Variable1":"-",
    "Variable2":" Test "
  }
  </code></pre>
  
  <p>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):</p>
  
  <pre class="lang-java prettyprint-override"><code>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());
  }
  </code></pre>
  
  <p>The above code should be working if the JSON looked something like this (yes, I said should because it does not work):</p>
  
  <pre><code>{
    "Variables": {
      "Variable1":"-",
      "Variable2":" Test "
    }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Thank you for your time and effort.</p>