How can I have JAX-RS return a Java 8 LocalDateTime property as a JavaScript-style Date String?

前端 未结 3 1790
谎友^
谎友^ 2021-01-02 06:44

I created a RESTful web service using JAX-RS method annotations:

@GET
@Path(\"/test\")
@Produces(MediaType.APPLICATION_JSON)
public MyThing test()
{
    MyTh         


        
3条回答
  •  孤城傲影
    2021-01-02 07:31

    Note: See UPDATE below

    I've never use LocalDateTime before, so I decided to do some testing. Here are my findings:

    • Jersy 2.13 and this provider (works out the box with no extra configuration)

      
          org.glassfish.jersey.media
          jersey-media-moxy
          ${jersey.version}
      
      
    • Jersey 2.13 with this provider (has support for JAXB annotation - dependency on jackson-module-jaxb-annotations), with custom adapter

      
          org.glassfish.jersey.media
          jersey-media-json-jackson
          ${jersey.version}
      
      
      public class LocalDateTimeAdapter extends XmlAdapter {
          @Override
          public LocalDateTime unmarshal(String s) throws Exception {
              return LocalDateTime.parse(s);
          }
          @Override
          public String marshal(LocalDateTime dateTime) throws Exception {
              return dateTime.toString();
          }   
      }
      
      // Getter for model class
      @XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
      public LocalDateTime getDateTime() {
          return dateTime;
      }
      
    • Resteasy 3.0.9 with this provider, (also has support for JAXB annotation - dependency on jackson-module-jaxb-annotations), with custom adapter (See above)

      
          org.jboss.resteasy
          resteasy-jackson2-provider
          ${resteasy.version}
      
      
    • Both Resteasy and Jersey with this dependency (also did not work without custom config, same as last two - with adapter)

      
          com.fasterxml.jackson.jaxrs
          jackson-jaxrs-json-provider
          2.4.0
      
      

      We need to make sure to register the JacksonJaxbJsonProvider


    So I guess it seems that any provider that uses Jackson, does not give you the deisred result, without some custom configuration, whether its through an adapter (as seen above) or some other custom configuration. The jersey-media-moxy provider doesn't use Jackson.


    UPDATE

    For the most part, the information above is incorrect.

    • MOXy does not work by default. It works for serialization by simply calling toString(), which may or may not be what you want, and it won't work when de-serializing. If you are using MOXy, until it supports Java8 time, you will need to use an XMLAdapter

    • Jackson you will need to configure its Java8 time support. This is the case with both Jersey and RESTEasy.

提交回复
热议问题