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

前端 未结 3 1882
谎友^
谎友^ 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:42

    I don't remember the exact details of why I did this but I got it working with the following dependencies:

    
      com.fasterxml.jackson.core
      jackson-databind
      2.4.2
      provided
    
    
      com.fasterxml.jackson.datatype
      jackson-datatype-jsr310
      2.4.2
    
    

    And the provider below:

    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public class JacksonContextResolver implements ContextResolver {
      private static final ObjectMapper om = init();
    
      @Override public ObjectMapper getContext(Class objectType) {
        return om;
      }
    
      private static ObjectMapper init() {
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        return om;
      }
    }
    

    Note that you can also play with the following flag:

    om.configure(WRITE_DATES_AS_TIMESTAMPS, true/false);
    

    (the actual class has more stuff in it but I believe it is irrelevant to this answer).

提交回复
热议问题