metalhamster
metalhamster

Reputation: 105

How can I specify the default MimeType returned by a REST resource with Jersey

I am creating a REST interface and have a resource 'data'. Now I want that an user can specify whether he wants the data as XML or as JSON. Therefore I have created two methods for the same path, one produces application/xml, the other produces application/json. Everything works fine, but how can I specify what should be returned, if an user doesn't set the 'Accept' header field?

My tests have shown that it is not always the same. Yesterday the default was application/xml, today my tests have failed, because as default application/json was returned.

How can I specify a default?

Code Snippet:

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION.XML)
public Object getDataAsXML() {
    // return data in XML format
}

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION_JSON)
public Object getDataAsJSON() {
    // return data in JSON format
}

Cheers,

metalhamster

Upvotes: 1

Views: 708

Answers (1)

Asif Bhutto
Asif Bhutto

Reputation: 3994

@Path("/myResource")
@Produces("text/plain")// doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. 
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html")
    public String doGetAsHtml() {
        ...
    }
}

The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. The doGetAsHtml method's @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text.

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}

The doGetAsXmlOrJson method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.

@Produce

Upvotes: 1

Related Questions