java反序列化为空_如何将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);

}

我期待打印“它是空的”.相反,我得到“它是”.显然,在转换为我的String对象类型时,Jackson不会将空字符串值视为NULL.

我读到了预期的地方.但是,这也是我想要避免的java.lang.String.有一个简单的方法吗?

解决方法:

杰克逊会为其他对象提供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;

}

标签:java,json,jackson

来源: https://codeday.me/bug/20190927/1823519.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值