如何使 readerForUpdating.readValue() 不覆盖非空值?

huangapple go评论103阅读模式
英文:

How to make readerForUpdating.readValue() not to override non null values?

问题

以下是您要翻译的内容:

我有以下两个类:

public class Simple {

    String a;
    String b;
    SubSimple subSimple;
}

public class SubSimple {

    String a;
    String b;
}

我应该对以下的objectMapper做哪些更改,以便将非空值保留为非空,不更新为null:

Simple simple = new Simple();
simple.setA("0a");
simple.setSubSimple(new SubSimple());
simple.getSubSimple().setA("00a");

String json = "{\"b\" : \"b\", \"subSimple\" : {\"b\" : \"b\"}}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

simple = objectMapper.readerForUpdating(simple).readValue(json);

System.out.println("simple : " + simple);

当前输出:

> simple : Simple{a='0a', b='b', subSimple=SubSimple{a='null', b='b'}}

所需输出:

> simple : Simple{a='0a', b='b', subSimple=SubSimple{a='00a', b='b'}}
英文:

I have following two classes :

public class Simple {

    String a;
    String b;
    SubSimple subSimple;
}

public class SubSimple {

    String a;
    String b;
}

What changes can I do to following objectMapper so that non null values are not updated to null :

        Simple simple = new Simple();
		simple.setA("0a");
		simple.setSubSimple(new SubSimple());
		simple.getSubSimple().setA("00a");

		String json = "{\"b\" : \"b\", \"subSimple\" : {\"b\" : \"b\"}}";
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);


		simple = objectMapper.readerForUpdating(simple).readValue(json);

		System.out.println("simple : " + simple);

Current output :

> simple : Simple{a='0a', b='b', subSimple=SubSimple{a='null', b='b'}}

Required :

> simple : Simple{a='0a', b='b', subSimple=SubSimple{a='00a', b='b'}}

答案1

得分: 1

尝试使用 com.fasterxml.jackson.annotation.JsonMerge 注解:

class Simple {

    String a;
    String b;

    @JsonMerge
    SubSimple subSimple;
}

或者在 com.fasterxml.jackson.databind.ObjectMapper 实例上启用它:

objectMapper.setDefaultMergeable(Boolean.TRUE);
英文:

Try to use com.fasterxml.jackson.annotation.JsonMerge annotation:

class Simple {

    String a;
    String b;

    @JsonMerge
    SubSimple subSimple;
}

or enable it on com.fasterxml.jackson.databind.ObjectMapper instance:

objectMapper.setDefaultMergeable(Boolean.TRUE);

huangapple
  • 本文由 发表于 2020年9月16日 23:38:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63923497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定