Adding a new key and value to the end of a json array in java

35 Views Asked by At

So I have this basic JSON file named Test.json:

[{"weight":{"1-1-2020":"50.0","1-2-2020":"50.0","1-3-2020":"50.0"}}]

It's a test file to mess around with. I also have this basic writting method:

 public void setWeight()
{
    try(FileReader reader = new FileReader("Test.json"))
    {
        JSONParser jsonParser = new JSONParser();

        Object obj = jsonParser.parse(reader);

        JSONArray jsonArray = (JSONArray) obj;

        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        JSONObject jObject = (JSONObject) jsonObject.get("weight");
        jObject.put("1-4-2020", "50.0");

        JSONObject userObject = new JSONObject();
        userObject.put("weight", jObject);

        JSONArray userList = new JSONArray();
        userList.add(userObject);

        try (FileWriter file = new FileWriter("Test.json")) 
        {
            file.write(userList.toJSONString());
            file.flush();
        } 
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

It first gets the keys and values of the file, and then adds a value and key with this line:

jObject.put("1-4-2020", "50.0");

This works fine:

[{"weight":{"1-1-2020":"50.0","1-2-2020":"50.0","1-3-2020":"50.0","1-4-2020":"50.0"}}]

But the moment I change the line to this:

jObject.put("1-5-2020", "50.0");

My file looks like this:

[{"weight":{"1-5-2020":"50.0","1-1-2020":"50.0","1-2-2020":"50.0","1-3-2020":"50.0","1-4-2020":"50.0"}}]

So my question is: why does this happen? And how do you make sure that the added value and key always end up at the end of the array, so something like this:

[{"weight":{"1-1-2020":"50.0","1-2-2020":"50.0","1-3-2020":"50.0","1-4-2020":"50.0","1-5-2020":"50.0"}}]   

I use the json-simple libary on visual studio code on windows.

0

There are 0 best solutions below