将java对象存储在json文件中

问题描述 投票:0回答:1

我打算将多个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();
    }
}

但它只工作一次,在我尝试添加更多对象之后,它只删除存储的最后一个并用新的替换它。

java json
1个回答
1
投票

我建议,你永远不会在你的文件中写一个Savefile对象,但已经开始使用List<Savefile>。然后通过以下步骤将更多对象附加到此列表更容易:

  1. 阅读您尚未创建的文件
  2. 将内容反序列化为List<Savefile>
  3. 将现在扩充列表写回文件(删除此文件中已存在的所有内容)

放入代码(使用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数组的文件,或者您完全跳过第一步。

© www.soinside.com 2019 - 2024. All rights reserved.