Java merge Objects (Json, ObjectMapper)

时间:2019-04-04 05:32:32

标签: java json

I wonna merge two POJO objects:

MyBean old = new MyBean();
MyBean diff = new MyBean();

In Json they look this:

diff: {"nat_udp_update_time":333}
old: {"nat_udp_update_time":15,"static_sip_local_port":1111}

result needed:

old: {"nat_udp_update_time":333,"static_sip_local_port":1111}

How i make this with use ObjectMapper or another lib?

3 个答案:

答案 0 :(得分:0)

您问了一个广泛的问题。解决此问题的一种方法是使用对象映射器将json读取到bean对象中,然后遍历“ diff” bean的成员并将其放入新bean中。

例如

ObjectMapper mapper = new ObjectMapper();
MyBean old = mapper.readValue("{\"nat_udp_update_time\":15,\"static_sip_local_port\":1111}", MyBean.class);
MyBean diff = mapper.readValue("{\"nat_udp_update_time\":333}", MyBean.class);
// go over all the stuff in diff and set it in old if it's different
if (diff.getNatUdpUpdateTime() != null && !diff.getNatUdpUpdateTime().equals(old.getNatUdpUpdateTime())) {
    old.setNatUdpUpdateTime(diff.getNatUdpUpdateTime());
}
// and so on ...

如果要使用bean来做很多这样的事情,可以查看mapstruct之类的库。如果您的json是简单的键/值对,请考虑使用Map<String, Object>而不是MyBean。请注意,上面的示例假定您不想设置null差异值。

答案 1 :(得分:0)

不需要依赖,您可以使用一些反射。

@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> T merge(T a, T b) {
    try {
        if (a == null)
            return b;
        else if (b == null)
            return a;
        Class<T> type = (Class) a.getClass();
        T c = type.getDeclaredConstructor().newInstance();
        for (Field field : a.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(a);
            field.set(c, value == null ? field.get(b) : value);
        }
        return c;
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Cannot merge objects!", e);
    }
}

请记住,这将仅合并以给定类型声明的字段,并且您的类型为此需要一个空的构造函数。

答案 2 :(得分:0)

JSON修补程序可以为您做到这一点。 Here an implem

示例:

JsonNode target = JsonPatch.apply(JsonNode patch, JsonNode source);