Search code examples
javarestjersey

Rest - Same MediaType in response as in request


I have a web service that consumes XML and JSON.
The output is currently always in XML.
Is it possible to produce the response in the same MediaType as the MediaType that was consumed?

What i need is:
The request is XML, the response is XML too.
The request is JSON, the response is JSON too.

My Code:

@Path("/calculate")
public class CalculationService
{
    @POST
    @Path("/magic")
    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Output calculate(Input input)
    {
        Output output = new Output();
        output.setValue1(...);
        output.setValue2(...);
        output.setValue3(...);

        return output;
    }
}

Solution

  • By default, the Web service delivers the response as MediaType.APPLICATION_XML.

    The MediaType can be controlled by setting the Accept-Header.

    By setting the value Accept: application/json, the response is delivered as MediaType.APPLICATION_JSON.