从POJO生成json模式

时间:2019-01-30 10:56:52

标签: java jsonschema

我需要从我的POJO生成json模式。要求是每个POJO必须作为一个单独的文件导出,并且json模式中的引用必须得到适当处理。这意味着该库应跟踪哪个POJO导出到哪个文件。我找到了这个库:https://github.com/mbknor/mbknor-jackson-jsonSchema,它可以正常工作,但似乎(或者至少我找不到这种选择),如果没有自定义编码,我将无法满足要求。您知道其他支持此功能的库吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Jackson使用以下Maven依赖项来生成JSON模式

<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>

然后您可以通过编写如下内容来生成模式

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);
    }
}
相关问题