【问题标题】:I want to render the data format of my choice dynamically in REST api我想在 REST api 中动态呈现我选择的数据格式
【发布时间】:2020-12-25 12:46:44
【问题描述】:

我必须在运行时呈现我选择的数据格式。

例如

public class Message {



@Id 
private String version;

private String title;

private String content;

private String sender;

private String url;
}

现在如果我点击 url http://localhost:8080/messages/12345/xml 它应该返回 xml 格式 如果我点击 url http://localhost:8080/messages/12345/json 那么我应该返回 json 格式

但终点应该相同 http://localhost:8080/messages/12345

我对 Spring boot 和 REST 非常陌生,这将是一个很大的帮助。

【问题讨论】:

    标签: spring-boot rest spring-data-jpa


    【解决方案1】:

    根据您的问题,对于 json,您不需要转换器或库 spring boot 有 jackson 库,因此它会自动将您的 pojo 转换为 json。对于 xml 响应,将 jackson-dataformat-xml 依赖项添加到您的项目中

    <dependency>
     <groupId>com.fasterxml.jackson.dataformat</groupId>
     <artifactId>jackson-dataformat-xml</artifactId>
     <version>2.9.8</version>
    </dependency>
    

    在返回响应时,像这样将 pojo 转换为 xml 响应

    Message message = new Message();
    message.setVersion();
    // set all the values if you want otherwise take the message object and pass
    XmlMapper xmlMapper = new XmlMapper();
    String xml = xmlMapper.writeValueAsString(message);
    

    这将返回 xml 响应

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 2017-12-14
      • 2021-11-15
      • 1970-01-01
      • 2019-01-03
      • 2021-10-21
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多