1

I'm trying to append JSON Object each time within an existing JSON Array. For that i'm using GSON libraries. Tried below code :

OrderIDDetailBean ord = new OrderIDDetailBean();
ord.uniqueID = "sadasdas0w021";
ord.orderID = "Nand";

ord.cartTotal = "50";
ord.date = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS").format(new Date());

try {
    JsonWriter writer = new JsonWriter(new FileWriter("D:\\file.json", true));

    writer.beginArray();
    writer.beginObject();

    writer.name("uniqueID").value(ord.uniqueID);
    writer.name("orderID").value(ord.orderID);
    writer.name("cartTotal").value(ord.cartTotal);
    writer.name("date").value(ord.date);
    writer.endObject();
    writer.endArray();

    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

But it created JSON array each time instead of appending.

Actual:

[  
   {  
      "uniqueID":"CHECKOUT_ES01",
      "orderID":"5001787761",
      "date":"07-02-2019 15:31:41.637",
      "cartTotal":"11.44"
   } 
]

[
   {  
      "uniqueID":"CHECKOUT_ES01",
      "orderID":"5001787767",
      "date":"07-02-2019 15:35:20.347",
      "cartTotal":"11.44"
   }
]

Expected :

[  
   {  
      "uniqueID":"CHECKOUT_ES01",
      "orderID":"5001787761",
      "date":"07-02-2019 15:31:41.637",
      "cartTotal":"11.44"
   },
   {  
      "uniqueID":"CHECKOUT_ES01",
      "orderID":"5001787767",
      "date":"07-02-2019 15:35:20.347",
      "cartTotal":"11.44"
   }
]

Any help would be great appreciated.

4
  • 1
    Not sure what you mean by "it add same structure again", but you should most likely open your file with new FileWriter("D:\\file.json", false), the true you're currently using means what you writes will be appended at the end of the existing content. Commented Feb 7, 2019 at 13:45
  • Yes i want to append data each time in existing file thats why its true Commented Feb 7, 2019 at 13:46
  • programcreek.com/java-api-examples/?code=alex-ac/LevelEditor/… See if you can glean stuff from this example. IIRC Factory and ObjectBuilders come into play normally. Commented Feb 7, 2019 at 13:48
  • it add same structure again so can you show what is the result? You do not show what you have originally and what you get, just what you want. Commented Feb 7, 2019 at 19:25

1 Answer 1

2

With your approach you might have a file that has many arrays each having one object. I suggest using Gson.fromJson(..) & Gson.toJson(..) instead of JsonWriter.

Assume the object you want to add is like:

@AllArgsConstructor
@Getter @Setter
public class OrderIDDetailBean {
    private String uniqueID;
    private Integer orderID;
    private Date date;
    private Double cartTotal;        
}

then appending new object would go like:

@Test
public void test() throws Exception {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    // construct Type that tells Gson about the generic type
    Type dtoListType = new TypeToken<List<OrderIDDetailBean>>(){}.getType();
    FileReader fr = new FileReader("test.json");
    List<OrderIDDetailBean> dtos = gson.fromJson(fr, dtoListType);
    fr.close();
    // If it was an empty one create initial list
    if(null==dtos) {
        dtos = new ArrayList<>();
    }
    // Add new item to the list
    dtos.add(new OrderIDDetailBean("23", 34234, new Date(), 544.677));
    // No append replace the whole file
    FileWriter fw  = new FileWriter("test.json");
    gson.toJson(dtos, fw);
    fw.close();        
}
Sign up to request clarification or add additional context in comments.

1 Comment

You really have to deserialize and reserialize the whole thing to add to it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.