Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON schema date

I would like to generate a JSON schema of a class with a java.util.Date field. For fields with type Date I am getting:

"fieldName" : { "type": "integer", "format": "UTC_MILLISEC" }

What i would like is something like:

"fieldName" :{ "type": "string", "format": "date-time" }

I would like this configuration to be global for all POJOS and not only for a specific POJO. So, an annotation on a specific class will not help me.

Thanks!

like image 969
galusben Avatar asked Apr 30 '26 22:04

galusben


1 Answers

This is just an example for the Dennis's answer demonstrating that SerializationFeature.WRITE_DATES_AS_TIMESTAMPS is actually taking into account by the Jackson schema generator.

public class JacksonSchema1 {

    public static class Bean {
        public String name;
        public Date date;
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
        mapper.acceptJsonFormatVisitor(mapper.constructType(Bean.class), visitor);
        JsonSchema jsonSchema = visitor.finalSchema();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
    }
}

Output:

{
  "type" : "object",
  "properties" : {
    "name" : {
      "type" : "string"
    },
    "date" : {
      "type" : "string",
      "format" : "DATE_TIME"
    }
  }
}
like image 134
Alexey Gavrilov Avatar answered May 03 '26 12:05

Alexey Gavrilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!