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

我正在尝试一个简单的JSON来反序列化到java对象。 但是,我获取了java.lang.String属性值的空String值。 在其余属性中,空值会转换为值(这就是我想要的)。

我的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 。 有一个简单的方法吗?

jackson会为其他对象提供null,但对于String,它会给出空字符串。

但是您可以使用Custom JsonDeserializer来执行此操作:

 class CustomDeserializer extends JsonDeserializer { @Override public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { JsonNode node = jsonParser.readValueAsTree(); if (node.asText().isEmpty()) { return null; } return node.toString(); } } 

在课堂上,你必须将它用于位置字段:

 class EventBean { public Long eventId; public String title; @JsonDeserialize(using = CustomDeserializer.class) public String location; } 

可以为String类型定义自定义反序列化器,覆盖标准String反序列化器:

 this.mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(String.class, new StdDeserializer(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); 

这样,所有String字段的行为方式都相同。