Santushti Sharma
Santushti Sharma

Reputation: 33

JSONObject not giving expected results

I wrote a code of java which adds the data present in array to an existing json file.

This is my code

public static void writeInJsonFile() {
  for(int i = 0; i < list.size(); ++i) { 
     String path = list[i][0];
     String id = list[i][2];
     String value = list[i][1];
     
     JSONObject root = mapper.readValue(new File(path), JSONObject.class);
     JSONObject valueJson = new JSONObject();
     valueJson.put("value", value);
     JSONObject idJson = new JSONObject();
     idJson.put("id", valueJson);
     root.put("system", idJson);

     FileWriter writer = new FileWriter(path);
     writer.write(String.valueOf(root));
     writer.close();
  }
}

List<List> list = [["FileName1","Value1","Id1"],[],[],[]...] It is writing the code at required path, but not appending it. Previous data gets deleted.

Expected Results

FileName1.json

{
  "system" : {
     id1 : {
       "value" : value
     },
     id3 : {
       "value" : value3
     },
     id2 : {
       "value" : value2
     }
  }
}

FileName2.json
{
  "system" : {
      id4 : {
         "value" : value4
       },
       id6 : {
         "value" : value6
       }
   }
}

Actual Results

FileName1.json

{
  "system" : {
     id2 : {
       "value" : value2
     }
}

FileName2.json
{
  "system" : {
     id6 : {
       "value" : value6
     }
}

How should i solve this problem ??

Upvotes: 0

Views: 284

Answers (1)

Dorian349
Dorian349

Reputation: 1589

You aren't collecting your JSONObject idJson = new JSONObject(); before trying to add a new value into it. So each time you open the file, you "erase" the old content.

You can do, subject to the existence of the "system" field (Make sure to check it first).

JSONObject idJson = root.getJSONObject("system");

Upvotes: 1

Related Questions