SpringBoot使用Jackson,全局反序列化去除字符串前后空格

方法一

继承SimpleModule

@Component
public class StringTrimModule extends SimpleModule {

	private static final long serialVersionUID = 1L;

	public StringTrimModule() {
		addDeserializer(String.class, new StdScalarDeserializer(String.class) {
			
			private static final long serialVersionUID = 1L;

			@Override
			public String deserialize(JsonParser p, DeserializationContext ctxt)
					throws IOException, JsonProcessingException {
				String value = p.getValueAsString();
				return value.trim();
			}
		});
	}
	
}

方法二、

@Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder
                        .deserializerByType(String.class, new StdScalarDeserializer(String.class) {
                        	
							private static final long serialVersionUID = 1L;

							@Override
                            public String deserialize(JsonParser jsonParser, DeserializationContext ctx)
                                    throws IOException {
                                return StringUtils.trimWhitespace(jsonParser.getValueAsString());
                            }
                        });
            }
        };
    }

 

你可能感兴趣的:(springboot)