Search code examples
javaarraysnetbeansfilereaderjson-simple

How to get a certain elements inside an array inside a jsonObject


I'm exporting some data in java using JSON then I'm reading that data and trying to get elements from an array inside the JSON object but I'm having issues.

I have tried a lot of things like

jsonObject.get("InGameCord").get("x")
Object Testo = jsonObject.get("InGameCord");
Testo.x

Things like that along with more that did not work so deleted the code.

This is the exported JSON file and im trying to access the InGameCord array X or Y.

{"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}

Here is my file reader code

FileReader reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
System.out.println("BaseName: "+jsonObject.get("BaseName"));
System.out.println("BaseID: "+jsonObject.get("BaseID"));
System.out.println("InGameCord: "+jsonObject.get("InGameCord"));

All of this works and exports the correct info.

So I'm trying to get let us say the X value of InGameCord.

int X = 463;

Solution

  • Given your JSON data {"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}:

    • "InGameCord" is the name of an array which can be instantiated as a JSONArray.
    • That array contains only one element: {"x":463,"y":451}.
    • That array element can be instantiated as a JSONObject. It contains two name/value pairs:

      • "x" with the value 463.
      • "y" with the value 451.

    So based on the code you provided, to instantiate the JSONArray:

    JSONArray numbers = (JSONArray) jsonObject.get("InGameCord");

    To retrieve the first (and only) element of the array into a JSONObject:

    JSONObject jObj = (JSONObject) numbers.get(0);

    To get the value for "x" into an int variable cast the Object returned by get() to a Number, and then get its intValue():

    int value = ((Number) jObj.get("x")).intValue();

    You can even do the whole thing in one line, but it's ugly:

    int y = ((Number) ((JSONObject) numbers.get(0)).get("y")).intValue();