【发布时间】:2015-06-15 09:42:16
【问题描述】:
我正在尝试一个简单的 JSON 来反序列化为 java 对象。但是,我得到了 java.lang.String 属性值的空 String 值。在其余属性中,空白值正在转换为 null 值(这是我想要的)。
下面列出了我的 JSON 和相关的 Java 类。
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);
}
我期待打印“它是空的”。相反,我得到“它是”。显然,Jackson 在转换为我的 String 对象类型时没有将空白字符串值视为 NULL。
我在某处读到它是预期的。但是,对于 java.lang.String,我也想避免这种情况。有简单的方法吗?
【问题讨论】: