Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...