简体   繁体   中英

Generate json schema from POJO

I need to generate json schema from my POJOs. The requirement is that every POJO must be exported as a separate file and the references inside the json schema must be handled appropriately. It means that the library should keep track of which POJO is exported to which file. I found this library: https://github.com/mbknor/mbknor-jackson-jsonSchema and it works fine but it seems (or at least i cannot find such option) that i can't accomplish the requirements without custom coding. Do you know any other library that supports this?

You can use Jackson to generate the JSON schema using the following maven dependencies

<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.module</groupId>
 <artifactId>jackson-module-jsonSchema</artifactId>
 <version>2.9.8</version>
</dependency>
<dependency>
 <groupId>org.reflections</groupId>
 <artifactId>reflections</artifactId>
 <version>0.9.11</version>
</dependency>

You can then generate the schema by writing something like this

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);

    Reflections reflections = new Reflections("my.pojo.model",new SubTypesScanner(false));
    Set<Class<?>> pojos = reflections.getSubTypesOf(Object.class);
    Map<String, String> schemaByClassNameMap = pojos.stream()
            .collect(Collectors.toMap(Class::getSimpleName, pojo -> getSchema(mapper, schemaGen, pojo)));
    schemaByClassNameMap.entrySet().forEach(schemaByClassNameEntry->writeToFile(schemaByClassNameEntry.getKey(),schemaByClassNameEntry.getValue()));

}

private static void writeToFile(String pojoClassName, String pojoJsonSchema) {
    try {
        Path path = Paths.get(pojoClassName + ".json");
        Files.deleteIfExists(path);
        byte[] strToBytes = pojoJsonSchema.getBytes();
        Files.write(path, strToBytes);
    }catch (Exception e){
        throw new IllegalStateException(e);
    }
}

private static String getSchema(ObjectMapper mapper,JsonSchemaGenerator schemaGenerator,Class clazz){
    try {
        JsonSchema schema = schemaGenerator.generateSchema(clazz);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
    }catch (Exception e){
        throw new IllegalStateException(e);
    }
}

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