Create a text/plain Jersey response

后端 未结 2 784
心在旅途
心在旅途 2020-12-17 02:08

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

相关标签:
2条回答
  • 2020-12-17 02:29

    1. @Provider

    For some reason the documentation does not mention that I need to annotate the MessageBodyWriter class with @Provider. I have done that...

    @Provider
    @Produces(MediaType.TEXT_PLAIN)
    public class PlainTextWriter implements MessageBodyWriter<Machine> {
    

    ... and now I see this message on start up.* (Good)

    INFO: Provider classes found:
      class com.blah.resources.PlainTextWriter
    

    I still get the exception,

    SEVERE: A message body writer for Java class java.util.ArrayList, 
    and Java type java.util.List<com.blah.beans.Machine>, 
    and MIME media type text/plain was not found
    
    • Without @Provider, you get this message on start-up: INFO: No provider classes found.

    2. Use the correct type

    The second part is that I was not implementing for the correct type. I had a List of beans. I assumed Jersey would be smart enough to understand how to serialize a list, but I guess it could do that in different ways. Here was my second change: (Note the addition of List)

    @Provider
    @Produces(MediaType.TEXT_PLAIN)
    public class PlainTextWriter implements MessageBodyWriter<List<Machine>>
    

    It is working now. It's pretty cool because now I have a generic plain/text implementation. I only have to implement the toPlainText method of my interface for each Bean. No sweat!

    3. Use the correct package.

    It broke again. Looking at the log I see this:

    INFO: Scanning for root resource and provider classes in the packages:
      com.my.project.resources
    ...
    INFO: No provider classes found.
    

    So I refactored my MessageBodyWriter into that package and it works again!

    0 讨论(0)
  • 2020-12-17 02:35

    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.

    0 讨论(0)
提交回复
热议问题