Reputation: 2520
I intend to store multiple java objects into a JSON file but I got no clue how to do so. That's my code :
private static final String JSONFILEPATH = "config.json";
public void addSavefile(Savefile sf){
ObjectMapper mapper = new ObjectMapper();
try{
mapper.writeValue(new File(JSONFILEPATH), sf);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But it works just once, after I try to add more objects it just deletes the last one stored and replaces it with the new one.
Upvotes: 0
Views: 1918
Reputation: 2542
I suggest, that you never write a single Savefile
object in your file but already start with a List<Savefile>
. Then it is much easier to append further objects to this list with the following steps:
List<Savefile>
Put into code (simplified with a Test
object instead of your Savefile
) this would look like:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
File file = new File("/home/user/test.json");
// step 1 – assuming you already habe or wrote a file with empty JSON list []
List<Test> tests = mapper.readValue(file, new TypeReference<List<Test>>(){});
// step 2
tests.add(new Test(4));
// step 3
mapper.writeValue(file, tests);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Test {
int a;
}
Annotations come from Lombok.
The trick with
new TypeReference<List<Test>>(){}
helps you to deserialize objects with generics. Keep in mind that before starting you either have to have a file with an empty JSON array or you skip the first step at all.
Upvotes: 2