How to deserialize a blank JSON string value to null for java.lang.String?

前端 未结 6 1432
既然无缘
既然无缘 2020-12-01 16:10

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

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 16:26

    Jackson will give you null for other objects, but for String it will give empty String.

    But you can use a Custom JsonDeserializer to do this:

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

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

提交回复
热议问题