我想要一個簡單的json去反序列化到java對象。然而,我爲java.lang.String屬性值獲得了空的String值。在其餘的屬性中,空值被轉換爲空值(這是我想要的)。如何反序列化一個空的json字符串值null爲java.lang.String
我JSON和Java類列舉如下:
JSON字符串:
{
"eventId" : 1,
"title" : "sample event",
"location" : ""
}
Java代碼:
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);
我期待打印「Is is null」。相反,我得到了「這是」。很顯然,傑克遜沒有將空字符串值視爲空值,同時轉換爲java.lang.String對象類型。 我在某個地方讀過它。不過,這也是我想要避免的java.lang.String。有沒有簡單的方法?
謝謝薩欽。這應該工作。 – Mayur
這也適用於我,但使用readValueAsTree()將該字符串包裹在額外的引號中。所以爲了避免它,我用jsonParser.readValueAs(String.class); – kopelitsa
@kopelitsa額外的引號問題可以通過「return node.asText();」解決。 – gce