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

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

    You might first like to see if there has been any progress on the Github issue requesting this exact feature.

    For those using Spring Boot: The answer from jgesser was the most helpful to me, but I spent a while trying to work out the best way to configure it in Spring Boot.

    Actually, the documentation says:

    Any beans of type com.fasterxml.jackson.databind.Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates.

    So here's jgesser's answer expanded into something you can copy-paste into a new class in a Spring Boot application

    @Configuration
    public class EmptyStringAsNullJacksonConfiguration {
    
      @Bean
      SimpleModule emptyStringAsNullModule() {
        SimpleModule module = new SimpleModule();
    
        module.addDeserializer(
            String.class,
            new StdDeserializer(String.class) {
    
              @Override
              public String deserialize(JsonParser parser, DeserializationContext context)
                  throws IOException {
                String result = StringDeserializer.instance.deserialize(parser, context);
                if (StringUtils.isEmpty(result)) {
                  return null;
                }
                return result;
              }
            });
    
        return module;
      }
    }
    

提交回复
热议问题