1

The code is as follow.Where I am checking the content type extracted from the header then I want to write the code and return the response from the same method.

        @POST
        @Produces(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_XML)
        public Response addMessage(Message message , @Context UriInfo uriInfo, 
        @HeaderParam ("content-type") String contentType) throws 
        URISyntaxException
        {
        //Conditional check based on the content type.
        if(contentType.equals("application/json")) {
                    return json;
                }else {
                    return xml;
        }
        }

How a rest API will return both Json and XML response depending on the input header?

Sajal
  • 11
  • 5
  • Format the code, and move question from title to body – oybek Jun 10 '19 at 12:54
  • 1
    You have to pass the request header Accept: application/json or application/xml – Raj Jun 10 '19 at 13:01
  • You should just return the Response built with the object to return, and let JAX-RS handle the serialization into XML or JSON, depending on which the client expects/prefers. – vlumi Jun 10 '19 at 13:16
  • I have annotated with @Produces tag in the method level to support of return of both type of data. But the compiler objects. – Sajal Jun 10 '19 at 13:41

1 Answers1

1

First , your usage of multiple @Produces on same method is incorrect. A String[] can be specified for all types that you wish to produce with @Produces , Annotation Type Produces

And for your main question, I agree with vlumi's comment that ,

You should just return the Response built with the object to return, and let JAX-RS handle the serialization into XML or JSON, depending on which the client expects/prefers

i.e. let the framework do it for you depending on Accept header as specified by client as Raj has already mentioned in comments,

You have to pass the request header Accept: application/json or application/xml

Jersey Multiple Produces

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • Correct, Thanks for your help. I can mention the types in the values tag inside the Produces annotation on the class level and also in the method level. And depending on the Accepts parameter the result will be serialized for the client. – Sajal Jun 11 '19 at 11:28