Reputation: 1613
This is the code I am working with (someone else's project):
public class MyResponse
public static Response success(String content) {
MyResponse aRsponse = response(content);
return Response.status(Status.OK).entity(aRsponse.getContent()).build();
}
public static MyResponse response(final String content) {
return MyResponse.builder().content(content).build();
}
The GET/POSTs that call the success method have @Produces(MediaType.TEXT_XML)
preceding them.
I have implemented some logic to determine if content
is an XML or JSON and was thinking I'd pass that in as a param to success. So something like:
public static Response success(String content, boolean isJson)
Now I need to set the media type of the Response (with an if/else). I know I need something along the lines of .type(MediaType.TEXT_XML);
but I can't seem to figure this out given the code that I have to work with and given the various examples and documentation I have found.
Any help or steering in the right direction would be appreciated. Thanks!
Upvotes: 1
Views: 4251
Reputation: 709
I assume that you are using JAX-RS, right?
Take a look at Response
object documentation. You are looking for the type
method.
http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.ResponseBuilder.html
To set a different MediaType
, your code would look like:
Response.status(Status.OK).type(MediaType.TEXT_XML).entity(aRsponse.getContent()).build();
When you write the code Response.attribute
, you are using the Builder Pattern. So, to change something into the new object that would be build, you have to use the appropriate method to set the value on the attribute for the new class.
Upvotes: 2
Reputation: 3667
Assuming you're using JAXB/JAX-RS, and latest version, you don't need to worry about such things. Just return the objects and let the implementation handle the rest. No need to programmatically set media type or build.
eg.
@GET
@Path("/xmlexample")
@Produces(MediaType.APPLICATION_XML)
public MyObject xml() {
return new MyObject();
}
@GET
@Path("/jsonexample")
@Produces(MediaType.APPLICATION_JSON)
public MyObject json() {
return new MyObject();
}
You just need to make sure your class has the right annotations eg. @XmlElement.
Upvotes: 1