如何将 java.lang.String 的空白 JSON 字符串值反序列化为 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30841981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to deserialize a blank JSON string value to null for java.lang.String?
提问by Mayur
I am trying a simple JSON to de-serialize in to java object. I am however, getting empty Stringvalues for java.lang.String
property values. In rest of the properties, blank values are converting to nullvalues(which is what I want).
我正在尝试使用简单的 JSON 反序列化为 java 对象。不过,我,让空字符串值,java.lang.String
属性值。在其余属性中,空白值正在转换为空值(这是我想要的)。
My JSON and related Java class are listed below.
下面列出了我的 JSON 和相关的 Java 类。
JSON string:
JSON 字符串:
{
"eventId" : 1,
"title" : "sample event",
"location" : ""
}
EventBeanclass POJO:
EventBean类 POJO:
public class EventBean {
public Long eventId;
public String title;
public String location;
}
My main class code:
我的主要课程代码:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
try {
File file = new File(JsonTest.class.getClassLoader().getResource("event.txt").getFile());
JsonNode root = mapper.readTree(file);
// find out the applicationId
EventBean e = mapper.treeToValue(root, EventBean.class);
System.out.println("It is " + e.location);
}
I was expecting print "It is null". Instead, I am getting "It is ". Obviously, Hymansonis not treating blank String values as NULL while converting to my Stringobject type.
我期待打印“它是空的”。相反,我得到“它是”。显然,Hymanson在转换为我的String对象类型时不会将空白字符串值视为 NULL 。
I read somewhere that it is expected. However, this is something I want to avoid for java.lang.Stringtoo. Is there a simple way?
我在某处读到这是预期的。但是,这也是我想要避免的java.lang.String。有没有简单的方法?
采纳答案by Sach141
Hymanson will give you null for other objects, but for String it will give empty String.
对于其他对象,Hymanson 将为您提供 null,但对于 String,它将为您提供空字符串。
But you can use a Custom JsonDeserializer
to do this:
但是您可以使用自定义JsonDeserializer
来执行此操作:
class CustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
if (node.asText().isEmpty()) {
return null;
}
return node.toString();
}
}
In class you have to use it for location field:
在课堂上,您必须将其用于位置字段:
class EventBean {
public Long eventId;
public String title;
@JsonDeserialize(using = CustomDeserializer.class)
public String location;
}
回答by jgesser
It is possible to define a custom deserializer for the String type, overriding the standard String deserializer:
可以为 String 类型定义自定义反序列化器,覆盖标准的 String 反序列化器:
this.mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StdDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String result = StringDeserializer.instance.deserialize(p, ctxt);
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
}
});
mapper.registerModule(module);
This way all String fields will behave the same way.
这样,所有 String 字段的行为方式都相同。
回答by Fletch
You might first like to see if there has been any progress on the Github issuerequesting this exact feature.
您可能首先想看看在 Github 问题上是否有任何要求此确切功能的进展。
For those using Spring Boot: The answer from jgesser was the most helpful to me, but I spent a while trying to work out the best way to configure it in Spring Boot.
对于那些使用 Spring Boot 的人:jgesser 的回答对我最有帮助,但我花了一段时间试图找出在 Spring Boot 中配置它的最佳方法。
Actually, the documentationsays:
实际上,文档说:
Any beans of type com.fasterxml.Hymanson.databind.Module are automatically registered with the auto-configured Hymanson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates.
任何 com.fasterxml.Hymanson.databind.Module 类型的 bean 都会自动注册到自动配置的 Hymanson2ObjectMapperBuilder 并应用于它创建的任何 ObjectMapper 实例。
So here's jgesser's answer expanded into something you can copy-paste into a new class in a Spring Boot application
因此,jgesser 的答案扩展为您可以将其复制粘贴到 Spring Boot 应用程序中的新类中
@Configuration
public class EmptyStringAsNullHymansonConfiguration {
@Bean
SimpleModule emptyStringAsNullModule() {
SimpleModule module = new SimpleModule();
module.addDeserializer(
String.class,
new StdDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser parser, DeserializationContext context)
throws IOException {
String result = StringDeserializer.instance.deserialize(parser, context);
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
}
});
return module;
}
}
回答by Karthik P
A simple work around would be to replace "" with null before deserializing the json string.
一个简单的解决方法是在反序列化 json 字符串之前用 null 替换 ""。
.replace("\"\"", "null")
.replace("\"\"", "null")
This way all blank string will be deserialized as null
这样所有的空白字符串都将被反序列化为 null