简体   繁体   中英

How can I make fasterXml ObjectMapper put a format property into schema for fields of the type long

How can I make an ObjectMapper set the format field for some properties in the generated schema of a class?

I'm trying to generate a schema for a java class using a FasterXml library:

<dependency>
  <groupId>com.fasterxml.jackson.module</groupId>
  <artifactId>jackson-module-jsonSchema</artifactId>
  <version>2.14.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.14.1</version>
  <scope>compile</scope>
</dependency>

Test:

@SneakyThrows
@Test
public void test() {
    ObjectMapper objectMapper = new ObjectMapper();
    SchemaFactoryWrapper schemaVisitor = new SchemaFactoryWrapper();
    objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(MyClass.class), schemaVisitor);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemaVisitor.finalSchema()));
}

@Data
public static class MyClass {
    private int myInt;
    private long myLong;
}

The result is like this:

{
   "type":"object",
   "id":"urn:jsonschema:........:MyClass",
   "properties":{
      "myInt":{
         "type":"integer"
      },
      "myLong":{
         "type":"integer"
      }
   }
}

Both types are good, but I'd like to have "format": "int64" set for the property myLong .

Json Schema does not introduce int64 type. There are only number and integer types. Take a look at the enum JsonFormatTypes . JsonSchema module uses it. To extend it you would have to extend a lot of classes and somehow trick internal mechanism to replace integer with int64 which at the end would generate misleading schema which would be understandable only for you. All other libs and tools do not recognise it. I propose to use com.fasterxml.jackson.annotation.JsonPropertyDescription annotation for long property:

class MyClass {

    private int myInt;

    @JsonPropertyDescription("int64")
    private long myLong;
}

Which will generate something like this:

{
  "type" : "object",
  "id" : "urn:jsonschema:com:example:MyClass",
  "properties" : {
    "myInt" : {
      "type" : "integer"
    },
    "myLong" : {
      "type" : "integer",
      "description" : "int64"
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM