问题描述
我正在尝试使用简单的 JSON 反序列化为 java 对象.但是,我为 java.lang.String
属性值获取了空的 String 值.在其余属性中,空白值正在转换为 null 值(这是我想要的).
I am trying a simple JSON to de-serialize in to java object. I am however, getting empty String values for java.lang.String
property values. In rest of the properties, blank values are converting to null values(which is what I want).
下面列出了我的 JSON 和相关的 Java 类.
My JSON and related Java class are listed below.
JSON 字符串:
{
"eventId" : 1,
"title" : "sample event",
"location" : ""
}
EventBean 类 POJO:
public class EventBean {
public Long eventId;
public String title;
public String location;
}
我的主类代码:
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);
}
我期待打印它是空的".相反,我得到它是".显然,在转换为我的 String 对象类型时,Jackson 不会将空白字符串值视为 NULL.
I was expecting print "It is null". Instead, I am getting "It is ". Obviously, Jackson is not treating blank String values as NULL while converting to my String object type.
我在某处读到这是预期的.但是,对于 java.lang.String 我也想避免这种情况.有没有简单的方法?
I read somewhere that it is expected. However, this is something I want to avoid for java.lang.String too. Is there a simple way?
推荐答案
对于其他对象,Jackson 会给你 null,但对于 String 它会给空 String.
Jackson will give you null for other objects, but for String it will give empty String.
但是您可以使用自定义 JsonDeserializer
来执行此操作:
But you can use a Custom JsonDeserializer
to do this:
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;
}
这篇关于如何将 java.lang.String 的空白 JSON 字符串值反序列化为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!