John D
John D

Reputation: 175

Updating JSON file using Collections Google/gson library

I have a list of ObjectA: List<ObjectA> listA; .

I am trying to print all listA into JSON file, then I use in my function that do it. Files.write(Paths.get(filename), Collections.singleton(json.toJson(listA)), StandardCharsets.UTF_8); And this is works fine. (Just to make it clear - the type of json is Gson (Gson json = new Gson())

But, I am trying to add the following line in the JSON file before closing json: }. i.e I am trying to add the following line: "SomeString: " + someIntValue/AtomicInteger value for example: sum: 8 at the end of the JSON file before as said }.

How can I do it without print print each object in listA with iterator? is it possible to make it easy as I do it for listA with one line? and somehow edit this, for example add listA before opening [

Upvotes: 1

Views: 76

Answers (1)

Arvid Heise
Arvid Heise

Reputation: 3634

The easiest way would be to wrap your List in an object and let gson do the hard work.

class ListAWithStatistics {
    List<ObjectA> listA;
    int someString;
}

This wrapper class would also help you to easily deserialize the produced json.

Upvotes: 2

Related Questions