如何使用Jackson将Object附加到现有JSON文件

时间:2017-05-15 14:00:34

标签: java json jackson

如何使用Jackson将对象附加到现有的JSON文件?

File file = new File("test.json");
if (!file.exists()) {
    file.createNewFile();
}

ObjectMapper mapper = new ObjectMapper();

ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
mapper.writeValue(file, wtf);

1 个答案:

答案 0 :(得分:0)

不确定wtf是什么,但杰克逊会为你绘制地图:

class Wtf {
    String  brand;
    boolean stinks;

    public String getBrand() {
       return brand;
    }
    public boolean getStinks() {
       return stinks;
    }
    public void setBrand(String brand) {
       this.brand = brand;
    }
    public void setStinks(boolean stinks) {
       this.stinks = stinks;
    }
}

// From your code...
ObjectMapper mapper = new ObjectMapper();

// Insert
Wtf wtf = new Wtf();
wtf.setBrand("Noodle");
wtf.setStinks(true);

ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
mapper.writeValue(file, wtf);

这是你的问题吗?