Monday, October 20, 2014

Creating a JSON Schema from a POJO

If you're documenting your REST API it might be useful to show the schema definition behind the JSON objects being used.  The JSON Schema format provides a definition similar to XML's XSD.

It isn't very difficult to generate a JSON schema with Jackson.  Given a simple POJO with some properties which includes a list of another simpler POJO:

public class SimplePojo {

 private Integer id;
 private String name;
 private String description;
 private List children;
 // getters and setters ommitted
}
public class SimplePojoChild {

 private Integer id;
 @JsonProperty("cName")
 private String childName;
 @JsonProperty("cDescription")
 private String childDescription;
 // getters and setters ommitted
}

We can use the Jackson JsonSchema Module to generate the Schema with code similar to this:
public class JsonSchemaGenerator {

 public static void main(String[] args) throws JsonProcessingException {
  ObjectMapper mapper = new ObjectMapper();
        SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
        mapper.acceptJsonFormatVisitor(SimplePojo.class, visitor);
        JsonSchema schema = visitor.finalSchema();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));

 }

}

This code would generate this json schema:
{
  "type" : "object",
  "id" : "urn:jsonschema:com:bmchild:model:SimplePojo",
  "properties" : {
    "children" : {
      "type" : "array",
      "items" : {
        "type" : "object",
        "id" : "urn:jsonschema:com:bmchild:model:SimplePojoChild",
        "properties" : {
          "cName" : {
            "type" : "string"
          },
          "id" : {
            "type" : "integer"
          },
          "cDescription" : {
            "type" : "string"
          }
        }
      }
    },
    "name" : {
      "type" : "string"
    },
    "description" : {
      "type" : "string"
    },
    "id" : {
      "type" : "integer"
    }
  }
}

The only downside is if you're using a different version of jackson (we were using one from the codehaus repo) you'll need to change your json annotations so it will print out correctly.

All the code can be found on My Github Account

No comments:

Post a Comment