【问题标题】:Generate json schema from POJO从 POJO 生成 json 模式
【发布时间】:2019-06-23 15:15:20
【问题描述】:

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

【问题讨论】:

    标签: java jsonschema


    【解决方案1】:

    您可以使用 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);
        }
    }
    

    【讨论】:

    • 感谢您的建议!我尝试的库是基于杰克逊的,我看不出有任何方法可以满足我的要求。我有什么想念的吗?
    • 你是否包含了 jackson-module-jsonSchema 依赖项?
    • github.com/mbknor/mbknor-jackson-jsonSchema 基于杰克逊。 mbknor 库似乎无法满足我的要求,所以我希望 jackson 也能提供同样的要求。
    • @PlamenPaskov 代码的更新版本现在也将写入文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2015-03-07
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2018-06-30
    相关资源
    最近更新 更多