如何将空的JSON字符串值反序列化为null的java.lang.String?

9 浏览
0 Comments

如何将空的JSON字符串值反序列化为null的java.lang.String?

我正在尝试将一个简单的JSON反序列化为Java对象。然而,对于java.lang.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);
    // 找出applicationId
    EventBean e = mapper.treeToValue(root, EventBean.class);
    System.out.println("It is " + e.location);
}

我原以为会打印"It is null"。但实际上,我得到的是"It is "。显然,Jackson在转换为我的String对象类型时,不把空字符串值视为NULL。

我在某个地方读到过这是预期的行为。然而,这是我想要避免的,即对于java.lang.String。有没有简单的方法?

0