简体   繁体   English

从POJO生成json模式

[英]Generate json schema from POJO

I need to generate json schema from my POJOs. 我需要从我的POJO生成json模式。 The requirement is that every POJO must be exported as a separate file and the references inside the json schema must be handled appropriately. 要求是每个POJO必须作为一个单独的文件导出,并且json模式中的引用必须得到适当处理。 It means that the library should keep track of which POJO is exported to which file. 这意味着该库应跟踪哪个POJO导出到哪个文件。 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. 我找到了这个库: https : //github.com/mbknor/mbknor-jackson-jsonSchema ,它工作正常,但似乎(或者至少我找不到这种选择)如果没有自定义编码,我将无法满足要求。 Do you know any other library that supports this? 您知道其他支持此功能的库吗?

You can use Jackson to generate the JSON schema using the following maven dependencies 您可以使用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>

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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