我打算将多个java对象存储到JSON文件中,但我不知道如何这样做。那是我的代码:
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();
}
}
但它只工作一次,在我尝试添加更多对象之后,它只删除存储的最后一个并用新的替换它。
我建议,你永远不会在你的文件中写一个Savefile
对象,但已经开始使用List<Savefile>
。然后通过以下步骤将更多对象附加到此列表更容易:
List<Savefile>
放入代码(使用Test
对象而不是Savefile
进行简化),这看起来像:
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;
}
注释来自龙目岛。
使用
new TypeReference<List<Test>>(){}
的技巧可以帮助您使用泛型反序列化对象。请记住,在开始之前,您必须拥有一个带有空JSON数组的文件,或者您完全跳过第一步。