我最近加入了 Web 服务世界,并开始使用 json 输入创建和更新 hibernate 实体。
以下 api 将 json 输入转换为新的 pojo 对象:
Pojo newObject=mapper.readValue(jsonInput,Pojo.class);
这与创建 api 配合得很好。
现在更新 api 怎么样:
我有一个很大的 pojo,我不想进入从 json 输入将每个值设置为 pojo 对象的长方法
我想要这样的东西:
Pojo existingPojo=getFromDatabase();
existingPojo=mapper.readValue(updateJsonValues,existingPojo);
saveToDatabase(existingPojo);
因此,无论 updateJsonValues 有什么属性,它们都会更新到现有的Pojo中。
这将是很大的帮助。提前致谢。
最佳答案
故事是,这就是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!
ObjectReader reader=mapper.readerForUpdating(test);
reader.readValue("{\"message\":\"Hello\"}");
System.out.println(test);
reader.readValue("{\"target\":\"World\"}");
System.out.println(test);
关于java - 将 JSON 映射到现有的 pojo 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53319618/