2015-06-15 26 views
6

我想要一個簡單的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。有沒有簡單的方法?

回答

4

傑克遜會給你null爲其他對象,但對於字符串它會給空字符串。

但是你可以使用自定義JsonDeserializer做到這一點:

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(); 
    } 

} 

在課堂上,你必須使用它的位置字段:

class EventBean { 
    public Long eventId; 
    public String title; 

    @JsonDeserialize(using = CustomDeserializer.class) 
    public String location; 
} 
+0

謝謝薩欽。這應該工作。 – Mayur

+2

這也適用於我,但使用readValueAsTree()將該字符串包裹在額外的引號中。所以爲了避免它,我用jsonParser.readValueAs(String.class); – kopelitsa

+0

@kopelitsa額外的引號問題可以通過「return node.asText();」解決。 – gce

3

它可以定義爲一個自定義解串器字符串類型,覆蓋標準字符串解串器:

this.mapper = new ObjectMapper(); 

SimpleModule module = new SimpleModule(); 

module.addDeserializer(String.class, new StdDeserializer<String>(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); 

這樣所有字符串字段的行爲方式相同。

相關問題