将JSON映射到现有的pojo对象

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

我最近加入了Web服务世界,并开始使用json输入创建和更新hibernate实体。

以下api将json输入转换为新的pojo对象:

Pojo newObject=mapper.readValue(jsonInput,Pojo.class);

这与创建apis很好地配合。

那么更新apis呢:

我有一个很大的pojo,我不想进入long方法将每个值设置为json输入的pojo对象

我想要的东西:

Pojo existingPojo=getFromDatabase();

existingPojo=mapper.readValue(updateJsonValues,existingPojo);

saveToDatabase(existingPojo);

因此,无论updateJsonValues具有什么属性,它们都会更新为existingPojo。

这将是很大的帮助。谢谢你提前。

java json jackson
2个回答
1
投票

故事是,这就是ObjectMapper一样的东西本来就一直在做的事情,没有别的办法:首先实例化一个对象,然后从JSON更新它。 唯一的障碍是没有readValue()式的快捷方式(它可能像updateValue()),所以它是一些字符更长,你需要使用readerForUpdating()来获得一个合适的读者,然后它的readValue()

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public String message="Nope";
    public String target="Nope";
    public String toString() {
        return message+" "+target+"!";
    }

    public static void main(String[] args) throws Exception {
        Test test=new Test();
        System.out.println(test);
        ObjectMapper mapper=new ObjectMapper();
        mapper.readerForUpdating(test).readValue("{\"message\":\"Hello\"}");
        System.out.println(test);
        mapper.readerForUpdating(test).readValue("{\"target\":\"World\"}");
        System.out.println(test);
    }
}

输出:

Nope Nope!
Hello Nope!
Hello World!


Edit: if it is needed repeatedly, the reader can be stored and re-used of course:
ObjectReader reader=mapper.readerForUpdating(test);
reader.readValue("{\"message\":\"Hello\"}");
System.out.println(test);
reader.readValue("{\"target\":\"World\"}");
System.out.println(test);

0
投票

我遇到了同样的问题,经过大量的挖掘后,我遇到了一个开源库MapStruct。它有助于java bean映射,并在应用程序启动时为您生成代码。它对我来说很好。搏一搏。

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