0

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.

Nope 69
  • 51
  • 5
  • The key and value are not in an array but in an object; the order of keys in an object does not matter. – Billy Brown Oct 06 '20 at 10:30
  • If you want to sort json then may be this link will give your answer. https://stackoverflow.com/questions/40513691/sorting-a-jsonarray-string-by-its-date-field-yyyy-mm-dd-hh-mm-ss-sss – Sanjay Oct 06 '20 at 10:34

0 Answers0