由于是Rest风格,使用的是RequestResponseBodyMethodProcessor
,我们模仿jackson的convert进行仿写
@PostMapping(value = "/properties",
consumes = "text/properties;charset=utf-8")
public Properties properties(@RequestBody Properties properties){
return properties;
}
public class PropertiesConvert extends AbstractGenericHttpMessageConverter<Properties> {
/**
* 支持的处理类型
*/
public PropertiesConvert() {
super(new MediaType("text","properties"));
}
/**
* 返回值处理
*/
@Override
protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
HttpHeaders httpHeaders = outputMessage.getHeaders();
Charset charset = httpHeaders.getContentType().getCharset();
charset = charset == null ? Charset.forName("utf-8") : charset;
OutputStream outputStream = outputMessage.getBody();
Writer writer = new OutputStreamWriter(outputStream,charset);
properties.store(writer,"my convert");
}
/**
* 入参转换
*/
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
HttpHeaders httpHeaders = inputMessage.getHeaders();
Charset charset = httpHeaders.getContentType().getCharset();
charset = charset == null ? Charset.forName("utf-8") : charset;
InputStream inputStream = inputMessage.getBody();
InputStreamReader reader = new InputStreamReader(inputStream,charset);
Properties properties = new Properties();
properties.load(reader);
return properties;
}
@Override
public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return readInternal(null,inputMessage);
}
}
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//由于json可以处理properties,如果不指定位置添加是添加到末尾,在选择convert处理时会优先选择json的而不是我们自定义的
converters.add(0,new PropertiesConvert());
}
}
我们没有指定返回媒体类型,因此是所有的都可以。但由于我们自定义的添加到了第一个位置,所以会用完没自定义的这个convert进行转换返回
来源:CSDN
作者:Mutou_ren
链接:https://blog.csdn.net/Mutou_ren/article/details/104081053