REST. Jersey. How to programmatically choose what type to return: JSON or XML?

后端 未结 3 1625
深忆病人
深忆病人 2021-02-04 11:53

I have 2 questions:

1. Can I create one class, annotate it with JAXB annotations(for XML support) and declare in web.xml

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 12:34

    No need for seperate classes, what you need is seperate methods:

    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Todo getXML() {
        Todo todo = new Todo();
        todo.setSummary("This is my first todo");
        todo.setDescription("This is my first todo");
        return todo;
    }
    

    Then in the client side, when you request for the service, you indicate in what format you want it:

    // Get XML
    System.out.println(service.path("rest").path("todo").accept(MediaType.TEXT_XML).get(String.class));
    // Get XML for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_XML).get(String.class));
    // Get JSON for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_JSON).get(String.class));
    

提交回复
热议问题