Skip to content

Instantly share code, notes, and snippets.

@annagapuz
Created August 28, 2019 18:39
Show Gist options
  • Save annagapuz/5874a4bb91d5d7536bf51e09f01bae76 to your computer and use it in GitHub Desktop.
Save annagapuz/5874a4bb91d5d7536bf51e09f01bae76 to your computer and use it in GitHub Desktop.
Generate JSON Schema from Java Object
public class JsonSchemaUtility {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// Serialize a LocalDate using the corresponding ISO formatter
objectMapper.registerModule(new SimpleModule().addSerializer(new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE)));
// Serialize a OffsetDateTime using the corresponding custom formatter
objectMapper.registerModule(new SimpleModule().addSerializer(new CustomOffsetDateTimeSerializer(OffsetDateTime.class)));
// Serialize a Year using the corresponding ISO formatter
objectMapper.registerModule(new SimpleModule().addSerializer(YearSerializer.INSTANCE));
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(objectMapper);
JsonSchema schema = schemaGen.generateSchema(YourObject.class);
schema.set$schema("http://json-schema.org/draft-07/schema#");
System.out.println(objectMapper.writeValueAsString(schema));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment