英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论