Spring引导通用字符串修剪序列化



我正在尝试在整个应用程序中实现通用的Spring trim序列化程序,但它似乎不起作用。如果我手动将这个序列化程序@JsonSerialize(using = StringTrimmerSerializer.class)放在一个特定的字段上,它确实可以工作——不确定我需要做什么才能使它在整个应用程序中工作,而不将它单独放在所有字段

import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.jackson.JsonComponent;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
@JsonComponent
public class StringTrimmerSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (!StringUtils.isEmpty(value)) {
value = value.trim();
}
gen.writeString(value);
}
}

更新:

尝试注册序列化程序,但问题相同

@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper(); //
//mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.registerModule(new SimpleModule().addSerializer(String.class, new StringTrimmerSerializer()));
return mapper;
}
/*
* @Bean public Module customSerializer() { SimpleModule module = new
* SimpleModule(); module.addSerializer(String.class, new
* StringTrimmerSerializer()); return module; }
*/
}

主类包:com.demo序列化程序包:com.demo.config

春季启动版本-2.2.5.RELEASEJackson数据绑定-2.10.2

在StringTrimmerSerializer 中添加构造函数

public StringTrimmerSerializer ()
public StringTrimmerSerializer (Class<String> s) {
super(s);
}

我能够通过将自定义序列化程序注册到jaskcosn的默认对象映射程序而不是创建ObjectMapper的新引用来解决问题。

@Configuration
public class JacksonConfiguration extends WebMvcConfigurationSupport {
@Autowired
private ObjectMapper objectMapper;
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
objectMapper.registerModule(new SimpleModule().addSerializer(String.class, new StringTrimmerSerializer()));
converter.setObjectMapper(objectMapper);
return converter;
}
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
}

最新更新