我正在尝试一个简单的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