适用于POJO的Java映射器/修补程序 [英] Java mapper/patcher for POJO

查看:77
本文介绍了适用于POJO的Java映射器/修补程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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字段会受到影响,所有其他字段(如namecreateDate)都应保留旧值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆