Changing Default JSON Time Format with RESTEasy 3.x

前端 未结 3 886
梦谈多话
梦谈多话 2021-02-13 22:35

I am using RESTEasy to implement a REST Service using JSON serialization. Currently, Dates are getting serialized to milliseconds since 1970. To improve compatibility, I would

3条回答
  •  清酒与你
    2021-02-13 23:38

    You need to register your ContextResolver implementation with Resteasy. You can do this by annotating your class with the @Provider annotation and allowing Resteasy to automatically scan it during startup, registering it in web.xml, or registering it in a class that extends javax.ws.rs.core.Application (if that is how you are bootstrapping Resteasy).

    Registering via Annotations

    @Provider
    public class JacksonConfig implements ContextResolver
    {
        private final ObjectMapper objectMapper;
    
        public JacksonConfig() throws Exception
        {
            objectMapper = new ObjectMapper.configure(
                               SerializationFeature.WRITE_DATE_AS_TIMESTAMPS, false);
        }
    
        @Override
        public ObjectMapper getContext(Class arg0)
        {
            return objectMapper;
        }
     }
    

    Verify that classpath scanning is enabled in your web.xml file like so:

    
        resteasy.scan
        true
    
    

    NOTE: If you are deploying this in JBoss 7 do not set the resteasy.scan context parameter as it is enabled by default.

    Registering via web.xml

    Add the following context parameter to your web.xml file. The value of the parameter should be the fully qualified class name of your ContextResolver.

    
          resteasy.providers
          foo.contextresolver.JacksonConfig
     
    

    Registering via Application

    If you are using an Application class to configure Resteasy you can add your provider to the set of services and providers to register with Resteasy like so:

    public class MyApp extends Application 
    {
        @Override
        public Set> getClasses() 
        {
            HashSet> set = new HashSet>(2);
            set.add(JacksonConfig.class);
            set.add(MyService.class);
            return set;
        }
    }
    

    More on standalone configuration HERE

提交回复
热议问题