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.
EDIT:
If it matters, I am using the embedded Jetty and Jersey options.
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…