Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating JsonSchema from pojo: how do I add "description" automatically?

I am trying to automatically generate JsonSchema from pojos in my project: The code looks like this:

ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);

When clazz is defined like this:

public class ZKBean
{
  public String anExample;
  public int anInt;
}

I end up with this:

{
  "type" : "object",
  "id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
  "properties" : {
    "anInt" : {
      "type" : "integer"
    },
    "anExample" : {
      "type" : "string"
    }
  }
}

All that is great. What I want to do is add the "description" key to the schema, so that I instead have something that looks like:

{
  "type" : "object",
  "id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
  "properties" : {
    "anInt" : {
      "type" : "integer",
      "description" : "Represents the number of foos in the system"
    },
    "anExample" : {
      "type" : "string",
      "description" : "Some descriptive description goes here"
    }
  }
}

I assumed there was some annotation I could just put on the fields in my ZKBean class, but after half a day of futzing I have not found one. Is this the way to go? Or do I need to do something with my Visitor?

Thanks, Jesse

like image 618
Jesse Avatar asked Jul 01 '14 17:07

Jesse


1 Answers

You can use the @JsonPropertyDescription annotation for generating json schema which works since Jackson 2.4.1. Here is an example:

public class JacksonSchema {
    public static class ZKBean {
        @JsonPropertyDescription("This is a property description")
        public String anExample;
        public int anInt;
    }

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

Output:

{
  "type" : "object",
  "id" : "urn:jsonschema:stackoverflow:JacksonSchema:ZKBean",
  "properties" : {
    "anExample" : {
      "type" : "string",
      "description" : "This is a property description"
    },
    "anInt" : {
      "type" : "integer"
    }
  }
}
like image 166
Alexey Gavrilov Avatar answered Oct 29 '22 00:10

Alexey Gavrilov