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

前端 未结 6 1449
既然无缘
既然无缘 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:33

    It is possible to define a custom deserializer for the String type, overriding the standard String deserializer:

    this.mapper = new ObjectMapper();
    
    SimpleModule module = new SimpleModule();
    
    module.addDeserializer(String.class, new StdDeserializer(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);
    

    This way all String fields will behave the same way.

提交回复
热议问题