简体   繁体   English

Rest Api 数据表示

[英]Rest Api Data Representation

I hava an Spring Boot Rest Api我有一个 Spring 启动 Rest Api

@RestController
public class BookController {

@Autowired
private BookRepository bookRepo;

@GetMapping(value = "/library/", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public List<Book> index(){
    Iterable<Book> bookIterable = bookRepo.findAll();
    List<Book> bookList = new ArrayList<>();
    bookIterable.forEach(a->bookList.add(a));
    return bookList;
}

My Homework is to add an additonal data representation so that when i put in the request i should can choose between which data representation i won't XML or JSON我的作业是添加一个额外的数据表示,这样当我提出请求时,我应该可以选择我不会 XML 或 JSON 的数据表示

Problem is问题是标头数据表示选项

I get even json how can i change between XML and Json when i do a get Request to the Endpoint我什至得到 json 我如何在 XML 和 Json 之间切换

To solve your problem you need to use the Accept header.要解决您的问题,您需要使用Accept header。 more details更多细节

The Content Type header indicates the type of data that you pass in the request. Content Type header 指示您在请求中传递的数据类型。 more details 更多细节

You need to make a request with the header, if you want to send and receive xml:如果您想发送和接收 xml,您需要向 header 提出请求:

 Accept: application/xml;
 Content-Type: application/xml;

usefull link 有用的链接

Ok now i found it my self what you need to know in order to use an XML output is first add to the pom.xml file following dependencies: Jackson XML Dataformat Ok now i found it my self what you need to know in order to use an XML output is first add to the pom.xml file following dependencies: Jackson XML Dataformat

        <dependency>
          <groupId>com.fasterxml.jackson.dataformat</groupId>
          <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
           <groupId>javax.xml.bind</groupId>
           <artifactId>jaxb-api</artifactId>
           <version>2.3.1</version>
        </dependency>

Then i just have to Add Jackson Annotations to my Entity Class



   @Entity
   @JacksonXmlRootElement
   public class Book {
    public Book() {
    }
    @JacksonXmlProperty(isAttribute = true)
    @Id
    @GeneratedValue
    private Integer id;
    @JacksonXmlProperty(isAttribute = true)
    private String title;
    @JacksonXmlProperty(isAttribute = true)
    private Integer numberOfCopies;

Thats it then i can Make a request with the Accept Header value application/xml就是这样,然后我可以使用 Accept Header 值 application/xml 发出请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM