Search code examples
javajsonjakarta-eejacksonwildfly

How to define Timestamp serialization to JSON globally in WildFly 26?


We migrated from an older WildFly version to the current 26. With that came the transition from codehouse Jackson to fasterxml.

We experienced, that timestamps are no longer serialized into JSON as unix miliseconds, but as a formated String. This works fine between server and client, but if you expect this format in the JSON intermediate format, other processes and tests do not work anymore.

I tried to find a global parameter to set to configure the old behavior, but it always was about having to implement something, like custom serializer or object mapper. Additionally, since the output comes from a generic SQL result, there is no possibility to set an annotation in some entity.

Is there a way to set a parameter in WildFly to globally set the output format back to the integer number without having to implement something?


Solution

  • There is no global setting. You'd have to use something like a JsonSerializer and register it with the ObjectMapper. Something like the following should work:

    public class TimestampJsonSerializer extends JsonSerializer<Timestamp> {
        @Override
        public void serialize(final Timestamp value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
            if (value != null) {
                gen.writeNumber(value.getTime());
            } else {
                gen.writeNull();
            }
        }
    }
    
    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public class JacksonProducer implements ContextResolver<ObjectMapper> {
    
        private final ObjectMapper json;
    
    
        public JacksonProducer() throws Exception {
            final SimpleModule module = new SimpleModule("TimestampSerializer");
            module.addSerializer(new TimestampJsonSerializer());
            this.json = new ObjectMapper()
                    .findAndRegisterModules()
                    .registerModule(module);
    
        }
    
        @Override
        public ObjectMapper getContext(Class<?> objectType) {
            return json;
        }
    }