jerseyjax-rspayarajsonb-apiyasson

Is it possible to set the default date format in JSON-B (Yasson) globally, instead of adding an annotation on every property?


I have using Jersey so far and I am doing my first implementation with JSON-B.

I am using Payara, so I working with Jersey and Yasson. I had an issue, because the serialized dates would always contain the "[UTC]" suffix.

I have managed to use an annotation on my date property, in my DTO. But I would like to configure that globally (in the JAX-RS application config?), instead of repeating myself on every date property. Is that possible? I haven't found anything so far...

Side question: I assume that it is possible to get rid of this "[UTC]" suffix, since it breaks all clients trying to parse the date. Any idea?


Solution

  • Thanks to this Github issue, I was able to solve my problem. Here is what I ended up writing in my code:

    JSONConfigurator.java:
    
    import javax.json.bind.Jsonb;
    import javax.json.bind.JsonbBuilder;
    import javax.json.bind.JsonbConfig;
    import javax.json.bind.config.PropertyNamingStrategy;
    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    
    @Provider
    public class JSONConfigurator implements ContextResolver<Jsonb> {
    
      @Override
      public Jsonb getContext(Class<?> type) {
        JsonbConfig config = getJsonbConfig();
        return JsonbBuilder
          .newBuilder()
          .withConfig(config)
          .build();
      }
    
      private JsonbConfig getJsonbConfig() {
        return new JsonbConfig()
          .withDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", null);
      }
    }
    

    And:

    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    import java.util.HashSet;
    import java.util.Set;
    
    @ApplicationPath("/api")    
    public class ApplicationConfig extends Application {
    
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> resources = new HashSet<Class<?>>();
            addRestResourceClasses(resources);
            resources.add(JSONConfigurator.class);
            return resources;
        }
    
    
        private void addRestResourceClasses(Set<Class<?>> resources) {
          ...
        }
    
    }