Generate Json Schema from POJO with a twist

前端 未结 3 1358
Happy的楠姐
Happy的楠姐 2020-12-28 18:53

What I have:

I\'m generating a JSON schema from a pojo. My code to generate the schema looks like so:

ObjectMapper mapper = new ObjectMapper();
Titl         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-28 19:06

    Storme's answer references org.codehaus, which is an older version of jackson. The following is similar but uses fasterxml (newer version).

    Pom:

    
        com.fasterxml.jackson.core
        jackson-core
        2.7.1
    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.7.1
    
    
        com.fasterxml.jackson.core
        jackson-annotations
        2.7.1
    
    
        com.fasterxml.jackson.module
        jackson-module-jsonSchema
        2.1.0
    
    

    Code:

    import ...TargetClass;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.jsonschema.JsonSchema;
    
    import java.io.IOException;
    
    public final class JsonSchemaGenerator {
    
        private JsonSchemaGenerator() { };
    
        public static void main(String[] args) throws IOException {
            System.out.println(JsonSchemaGenerator.getJsonSchema(TargetClass.class));
        }
    
        public static String getJsonSchema(Class clazz) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
            JsonSchema schema = mapper.generateJsonSchema(clazz);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
        }
    
    }
    

提交回复
热议问题