在项目开发中需要多数以json的数据格式向后台传输数据以及在页面中展示数据,但是还有一些需要xml或者peoperties等
Accept:告诉服务器,客户端支持的数据类型。
Content-Type:服务器通过这个头,接收的数据的类型
一、全部转换为在页面中以xml的形式展示
以xml的形式展示需要先有解析包,解析包根据实际情况而定
//扩展信息转换类
@Slf4j
@Configuration
public class MyWebconfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("converters:"+converters.size());
//使用xml作为第一解析方式
converters.add(0,new MappingJackson2XmlHttpMessageConverter());
}
}
二、解析某一个具体的类
1、定义自定义自媒体解析方式
public class MyMessageConverter extends AbstractHttpMessageConverter<Person> {
public MyMessageConverter(){
super(MediaType.valueOf("application/properties-person"));
setDefaultCharset(Charset.forName("UTF-8"));
}
@Override
protected boolean supports(Class<?> aClass) {
return aClass.isAssignableFrom(Person.class);
}
@Override
protected Person readInternal(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
InputStream body = httpInputMessage.getBody();
Properties properties=new Properties();
properties.load(body);
Person person=new Person();
person.setAge(Integer.valueOf(properties.getProperty("person.age")));
person.setName(properties.getProperty("person.name"));
return person;
}
@Override
protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
OutputStream body = httpOutputMessage.getBody();
Properties properties=new Properties();
properties.setProperty("person.age",String.valueOf(person.getAge()));
properties.setProperty("person.name",person.getName());
properties.store(new OutputStreamWriter(body,getDefaultCharset()),"niahi");
}
}
测试
//consumes :Content-type
//produces :Accept
@PostMapping(value = "/person/json/to/proper",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = "application/properties-person")//Accept
public Person person(@RequestBody Person person) {
return person;
}
@PostMapping(value = "/person/proper/to/json",
consumes = "application/properties-person",//
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Person person2(@RequestBody Person person) {
return person;
}
测试
![](https://img.haomeiwen.com/i12616589/7d591791ae17ad64.png)
![](https://img.haomeiwen.com/i12616589/a6955b283161d0e6.png)
网友评论