适用于POJO的Java映射器/修补程序 [英] Java mapper/patcher for POJO
问题描述
我有以下Java模型:
I have a following Java model:
public class Product {
private String name;
private String description;
private Date createDate;
public Product(String name, String description, Date createDate) {
this.name = name;
this.description = description;
this.createDate = createDate;
}
...
}
我创建了Product
的实例:
Date date = new Date();
Product product = new Product("Test name", "Test description", date);
assertTrue("Test name", product.getName())
assertTrue("Test description", product.getDescription())
assertTrue(date, product.getDate());
此外,我还有以下Map
:
Map<String, Object> patchMap = new HashMap<>();
patchMap.put("description", "New description");
我需要用此patchMap
中的值修补现有的product
对象.只有description
字段会受到影响,所有其他字段(如name
和createDate
)都应保留旧值.
I need to patch existing product
object with a values from this patchMap
. Only description
field should be affected, all other, like name
and createDate
should remain the old values.
我需要这样的东西:
product = mapper.patch(product, patchMap);
assertTrue("Test name", product.getName())
assertTrue("New description", product.getDescription())
assertTrue(date, product.getDate());
您能否建议一个Java映射库(并显示一个示例),它可以提供开箱即用的这种修补功能.
Could you please suggest a Java mapping library(and show an example) that can provide a functionality for such kind of patching out of the box.
推荐答案
您可以使用Jackson来做到这一点.
You could do this with Jackson.
它的ObjectMapper
有一个名为readerForUpdating
的方法,可以用新数据更新现有结构.
Its ObjectMapper
has a method called readerForUpdating
that can update an existing structure with new data.
ObjectMapper mapper = ...
String json = "{\"description\": \"new description\"}";
mapper.readerForUpdating(objectToUpdate).readValue(json);
如果您不想提供JSON输入,也可以使用Jackson API中提供的其他方法跳过此步骤.
If you donot want to provide JSON input, it is also possible to skip this step using other methods provided in the Jackson API.
这篇关于适用于POJO的Java映射器/修补程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!