I have some code that works, but I am looking for a better way to do it. I have a RESTful web API that I want to support JSON, XML, and TEXT media types. The JSON and XML is easy with a JAXB annotated "bean" class. I just got text/plain to work, but I wish Jersey was a little more intelligent and would be able to convert a list of my beans, List<Machine>
to a string using toString
.
Here is the Resource class. The JSON and XML media types use a JAXB annotated bean class. The text plain uses a custom string format (basically the stdout representation of a command).
@Path("/machines")
public class MachineResource {
private final MachineManager manager;
@Inject
public MachineResource(MachineManager manager) {
this.manager = manager;
}
@GET @Path("details/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Machine> details() {
return manager.details();
}
@GET @Path("details/")
@Produces({ MediaType.TEXT_PLAIN })
public String detailsText() {
StringBuilder text = new StringBuilder();
for(Machine machine : manager.details()) {
text.append(machine.toString());
}
return text.toString();
}
Is there a better way to do this with Jersey automatically converting to a string, so I only have to implement one method here? (That can handle all 3 media types)
I see that I can implement a MessageBodyWriter, but that seems like a lot more trouble.
If it matters, I am using the embedded Jetty and Jersey options.
Thanks!
Implementing a MessageBodyReader
/Writer
would be what you need to do in order to do the following:
@GET @Path("details/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
public List<Machine> details() {
return manager.details();
}
It's not very much code to write, and if you are able to write it generic enough you will be able to get some re-use out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With