Generate JSON schema from java class

ぐ巨炮叔叔 提交于 2019-12-03 04:14:37
StormeHawke

I ran into a need to do this myself, but needed to get the latest schema spec (v4 as of this post). My solution is the first answer at the link below: Generate Json Schema from POJO with a twist

Use objects from the org.codehaus.jackson.map package rather than the com.fasterxml.jackson.databind package. If you're following the instructions on this page then you're doing it wrong. Just use the jackson-mapper module instead.

Here's the code for future googlers:

private static String getJsonSchema(Class clazz) throws IOException {
    org.codehaus.jackson.map.ObjectMapper mapper = new ObjectMapper();
    //There are other configuration options you can set.  This is the one I needed.
    mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true);

    JsonSchema schema = mapper.generateJsonSchema(clazz);

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
}

One such tool is Jackson JSON Schema module:

https://github.com/FasterXML/jackson-module-jsonSchema

which uses Jackson databind's POJO introspection to traverse POJO properties, taking into account Jackson annotations, and produces a JSON Schema object, which may then be serialized as JSON or used for other purposes.

Use JJschema. It can generate draft 4 compliant JSON schemas. Refer this post http://wilddiary.com/generate-json-schema-from-java-class/ for details.

Though Jackson Json Schema module can too generate schema but it can, as of today, only generate draft 3 compliant schemas only.

public static String getJsonSchema(Class clazz) throws IOException {
         Field[] fields = clazz.getDeclaredFields();
         List<Map<String,String>> map=new ArrayList<Map<String,String>>();
         for (Field field : fields) {
             HashMap<String, String> objMap=new  HashMap<String, String>();
             objMap.put("name", field.getName());
             objMap.put("type", field.getType().getSimpleName());
             objMap.put("format", "");
             map.add(objMap);
         }
         ObjectMapper mapper = new ObjectMapper();
         String json = mapper.writeValueAsString(map);

       return json;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!