Jam1
Jam1

Reputation: 649

Loop through json file appending key value to List

I am trying to loop through a JSON file and append the value each time to patientList. So far I believe I have done the hard part, however the simplest part seems to be taking a lot of time, that is appending the values to patientList. My getJsonFile method gets the path of the JSON file. The format of the JSON file is below. I am able to print jsonArray so I know I am good up to that point, but lost after that.

Json file.

[{"patient":1},{"patient":2},{"patient":3},{"patient":4},{"patient":5},{"patient":6},{"patient":7},{"patient":8},{"patient":9}]

getJsonFile method.

private List<Integer> getJsonFile(String path)
{
    List<Integer> patientList = new ArrayList<>();

    try (FileReader reader = new FileReader(path))
    {
        JSONParser jsonParser = new JSONParser();

        JSONArray jsonArray = (JSONArray)jsonParser.parse(reader);
        System.out.println(jsonArray);


        // Update patientList
        for (int i = 0; i < jsonArray.size(); i++ )
        {

            patientList.add(jsonArray(i));
        }
    }
    catch(IOException | ParseException | NullPointerException e)
    {
        e.printStackTrace();
    }

    return patientList;
}

Upvotes: 0

Views: 402

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

Your JSONArray contains objects: {"patient":1}

So you could not add patientList.add(jsonArray(i));

You have to access the int value inside that object:

JSONObject patient = jsonArray.getJsonObject(i);
patientList.add(patient.getInt("patient");

Edit

Well. You are using the simple-json library with quite limit feature and outdated. In this case you have to cast the data yourself:

JSONObject patient = (JSONObject)jsonArray.get(i);
patientList.add((Integer)patient.get("patient");

I recommend you remove this lib and use existing JSON feature of Java. If you want more advance feature, Jackson/GSon is the library to use.

Upvotes: 1

Related Questions