MessageConvert
2018-12-26 本文已影响0人
FynnLiu
简要描述:
- 响应对象序列化配置,在默认的json序列化规则无法满足我们的需求时,需要自定义序列化规则,以下以MappingJackson2HttpMessageConverter为例子
step1:
自定义CustomeMappingJackson2HttpMessageConverter
public class CustomeMappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
try {
writePrefix(generator, object);
Class<?> serializationView = null;
Object value = object;
if (value instanceof MappingJacksonValue) {
MappingJacksonValue container = (MappingJacksonValue) object;
value = container.getValue();
serializationView = container.getSerializationView();
}
if (serializationView != null) {
this.objectMapper.writerWithView(serializationView).writeValue(generator, value);
}
else {
this.objectMapper.writeValue(generator, value);
}
writeSuffix(generator, object);
generator.flush();
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
}
}
}
step2:
servletConfig配置,最重要的是JacksonUtil.getObjectMapper(),获得自定义的mapper
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Charset charset = Charset.forName("UTF-8");
CustomeMappingJackson2HttpMessageConverter jacksonConverter = new CustomeMappingJackson2HttpMessageConverter();
jacksonConverter.setObjectMapper(JacksonUtil.getObjectMapper());
jacksonConverter.setSupportedMediaTypes(Lists.newArrayList(new MediaType("application", "json", charset),
new MediaType("application", "*+json", charset)));
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(charset);
converters.add(stringConverter);
converters.add(jacksonConverter);
converters.add(new FormHttpMessageConverter());
converters.add(new ByteArrayHttpMessageConverter());
}
step3:
统一处理时间格式,null 序列化规则,timeZone设置,金额格式化,敏感字掩码等
// 注册反序列化
jacksonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 注册序列化
jacksonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
// sp.setNullValueSerializer(new NullSerializer());
jacksonMapper.setSerializerProvider(sp);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jacksonMapper.setDateFormat(dateFormat);
// 时间输出为时间戳
jacksonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
jacksonMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
jacksonMapper.setSerializerFactory(
jacksonMapper.getSerializerFactory().withSerializerModifier(new CustomBeanSerializerModifier()));