如何将java.lang.String的空白JSON字符串值反序列化为null? [英] How to deserialize a blank JSON string value to null for java.lang.String?

查看:1623
本文介绍了如何将java.lang.String的空白JSON字符串值反序列化为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用简单的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 class POJO:

EventBean class 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。

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?

推荐答案

杰克逊会为其他对象提供null,但对于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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆