Generate JSON schema from Java class

user3587174 picture user3587174 · Oct 5, 2014 · Viewed 78.7k times · Source

I have a POJO class:

public class Stock {
 int id;
 String name;
 Date date;
}

Are there any annotations or development framework/API that can convert POJO to JSON schema like below:

{"id":
      {             
        "type" : "int"
      },
"name":{   
        "type" : "string"
       }
"date":{
        "type" : "Date"
      }
}

And also I can expand the schema to add information like "Required" : "Yes", description for each field, etc., by specifying some annotations or configurations on POJO and can generate JSON Schema like below:

{"id":
      {             
        "type" : "int",
        "Required" : "Yes",
        "format" : "id must not be greater than 99999",
        "description" : "id of the stock"
      },
"name":{   
        "type" : "string",
        "Required" : "Yes",
        "format" : "name must not be empty and must be 15-30 characters length",
        "description" : "name of the stock"
       }
"date":{
        "type" : "Date",
        "Required" : "Yes",
        "format" : "must be in EST format",
        "description" : "filing date of the stock"
      }
}

Answer

StormeHawke picture StormeHawke · Jan 13, 2015

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