web 数据返回内容格式 josn xml协商

[复制链接]
发表于 2025-9-2 11:00:45 | 显示全部楼层 |阅读模式
一套体系适配多端数据返回

多端内容适配

默认规则

SpringBoot 多端内容适配。

  • 基于请求头内容协商:(默认开启)
    客户端向服务端发送请求,携带HTTP标准的Accept请求头。Accept: application/json、text/xml、text/yaml,服务端根据客户端请求头盼望的数据范例进行动态返回
  • 基于请求参数内容协商:(需要开启)
    发送请求 GET /projects/spring-boot?format=json,匹配到 @GetMapping("/projects/spring-boot"),根据参数协商,优先返回 json 范例数据【需要开启参数匹配设置】,发送请求 GET /projects/spring-boot?format=xml,优先返回 xml 范例数据
基于请求参数返回xml

引入支持写出xml内容依赖
  1. <!-- 支持写出xml格式 -->
  2. <dependency>
  3.     <groupId>com.fasterxml.jackson.dataformat</groupId>
  4.     <artifactId>jackson-dataformat-xml</artifactId>
  5. </dependency>
复制代码
标注注解@JacksonXmlRootElement,可以写出为xml文档
  1. @JacksonXmlRootElement
  2. public class TUser {
  3.     private Long id;
  4.     private String loginName;
  5.     private String nickName;
  6.     private String passwd;
  7.                
  8.                 // getter,setter
  9. }
复制代码
开启基于请求参数的内容协商
  1. # spring配置
  2. spring:
  3.   # MVC配置
  4.   mvc:
  5.     # 内容协商配置
  6.     content-negotiation:
  7.       # 是否优先使用参数来决定返回类型,默认参数名:format
  8.       favor-parameter: true
  9.       # 用于指定返回类型参数的名称
  10.       parameter-name: type
复制代码
测试

自定义内容返回yaml

引入支持yaml格式依赖
  1. <!-- yaml格式支持 -->
  2. <dependency>
  3.         <groupId>com.fasterxml.jackson.dataformat</groupId>
  4.         <artifactId>jackson-dataformat-yaml</artifactId>
  5. </dependency>
复制代码
修改内容协商方式,自定义yaml内容范例
  1. # spring配置
  2. spring:
  3.   # MVC配置
  4.   mvc:
  5.     # 内容协商配置
  6.     content-negotiation:
  7.       # 是否优先使用参数来决定返回类型,默认参数名:format
  8.       favor-parameter: true
  9.       # 用于指定返回类型参数的名称
  10.       parameter-name: type
  11.       # 默认返回范例      default-content-type: application/json      # 新增媒体范例      media-types:        # 指定yaml格式        yaml: text/yaml
复制代码
编写自定义的YAML范例HTTP消息转换器MyYamlHttpMessageConverter ,把对象写出成YAML
  1. package com.keepc.bootyaml.component;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
  4. import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
  5. import org.springframework.http.HttpInputMessage;
  6. import org.springframework.http.HttpOutputMessage;
  7. import org.springframework.http.MediaType;
  8. import org.springframework.http.converter.AbstractHttpMessageConverter;
  9. import org.springframework.http.converter.HttpMessageNotReadableException;
  10. import org.springframework.http.converter.HttpMessageNotWritableException;
  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.nio.charset.Charset;
  14. /**
  15. * 自定义的YAML类型HTTP消息转换器,继承自AbstractHttpMessageConverter。
  16. * 用于支持将对象转换为YAML格式,并能被Spring MVC框架在处理HTTP请求和响应时使用。
  17. */
  18. public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
  19.     private ObjectMapper objectMapper = null; // 用于对象到YAML的转换
  20.     /**
  21.      * 构造函数,初始化消息转换器,配置支持的媒体类型为text/yaml,并配置YAML序列化器。
  22.      */
  23.     public MyYamlHttpMessageConverter() {
  24.         // 配置支持的媒体类型
  25.         super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
  26.         // 配置YAML工厂,禁用文档开始标记
  27.         YAMLFactory factory = new YAMLFactory()
  28.                 .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
  29.         this.objectMapper = new ObjectMapper(factory);
  30.     }
  31.     /**
  32.      * 判断当前转换器是否支持指定的类。
  33.      *
  34.      * @param clazz 待判断的类
  35.      * @return 总是返回true,表示支持所有类型的对象转换。
  36.      */
  37.     @Override
  38.     protected boolean supports(Class<?> clazz) {
  39.         return true;
  40.     }
  41.     /**
  42.      * 读取HTTP消息体,将其转换为对象。此方法在处理@RequestBody注解时被调用。
  43.      *
  44.      * @param clazz        目标对象的类
  45.      * @param inputMessage HTTP输入消息
  46.      * @return 转换后的对象
  47.      * @throws IOException                     输入输出异常
  48.      * @throws HttpMessageNotReadableException 消息不可读异常
  49.      */
  50.     @Override
  51.     protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
  52.             throws IOException, HttpMessageNotReadableException {
  53.         return null; // 此处需要根据实际需求实现对象的读取和转换逻辑
  54.     }
  55.     /**
  56.      * 将对象写入HTTP消息体。此方法在处理@ResponseBody注解时被调用。
  57.      *
  58.      * @param methodReturnValue 方法返回值
  59.      * @param outputMessage     HTTP输出消息
  60.      * @throws IOException                     输入输出异常
  61.      * @throws HttpMessageNotWritableException 消息不可写异常
  62.      */
  63.     @Override
  64.     protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage)
  65.             throws IOException, HttpMessageNotWritableException {
  66.         // 使用try-with-resources语句确保输出流被正确关闭
  67.         try (OutputStream os = outputMessage.getBody()) {
  68.             this.objectMapper.writeValue(os, methodReturnValue);
  69.         } // end try-with-resources
  70.     }
  71. }
复制代码
增长HttpMessageConverter组件,专门负责把对象写出为yaml格式
  1. @Configuration // 表示这是一个配置类
  2. public class MyConfig implements WebMvcConfigurer {
  3.     /**
  4.      * 配置消息转换器,用于支持将对象转换为YAML格式的消息。
  5.      *
  6.      * @param converters 用于存储消息转换器的列表,这个列表允许Web应用程序处理不同的数据格式。
  7.      */
  8.     @Override
  9.     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  10.         // 向消息转换器列表中添加一个自定义的YAML消息转换器
  11.         converters.add(new MyYamlHttpMessageConverter());
  12.     }
  13. }
复制代码
测试


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表