Skip to content

Generate JSON Schema draft 4 with Polymorphism using Jackson annotations

License

Notifications You must be signed in to change notification settings

ratulm/mbknor-jackson-jsonSchema

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

96 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Jackson jsonSchema Generator

Build Status Maven Central

This projects aims to do a better job than the original jackson-module-jsonSchema in generating jsonSchema from your POJOs using Jackson @Annotations.

Current version: 1.0.10

Highlights

  • JSON Schema Draft v4
  • Supports polymorphism (@JsonTypeInfo, MixIn, and registerSubtypes()) using JsonSchema's oneOf-feature.
  • Supports schema customization using:
    • @JsonSchemaDescription/@JsonPropertyDescription
    • @JsonSchemaFormat
    • @JsonSchemaTitle
    • @JsonSchemaDefault
  • Supports many Javax-validation @Annotations
  • Works well with Generated GUI's using https://github.com/jdorn/json-editor
    • (Must be configured to use this mode)
    • Special handling of Option-/Optional-properties using oneOf.
  • Supports custom Class-to-format-Mapping

Benefits

  • Simple implementation - Just one file (for now..)
  • Implemented in Scala (Built for 2.10, 2.11 and 2.12)
  • Easy to fix and add functionality

Project status

We're currently using this codebase in an ongoing (not yet released) project at work, and we're improving the jsonSchema-generating code when we finds issues and/or features we need that not yet is supported.

I would really appreciate it if other developers wanted to start using and contributing improvements and features.

Dependency

This project publishes artifacts to central maven repo.

The project is also compiled using Java 8. This means that you also need to use Java 8.

Artifacts for both Scala 2.10, 2.11 and 2.12 is now available (Thanks to @bbyk for adding crossBuild functionality).

Using Maven

Add this to you pom.xml:

<dependency>
    <groupId>com.kjetland</groupId>
    <artifactId>mbknor-jackson-jsonschema_2.12</artifactId>
    <version>1.0.10</version>
</dependency>    

Using sbt

Add this to you sbt build-config:

"com.kjetland" % "mbknor-jackson-jsonschema" %% "1.0.10"

Code - Using Scala

This is how to generate jsonSchema in code using Scala:

    val objectMapper = new ObjectMapper
    val jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper)
    val jsonSchema:JsonNode = jsonSchemaGenerator.generateJsonSchema(classOf[YourPOJO])
    
    val jsonSchemaAsString:String = objectMapper.writeValueAsString(jsonSchema)

This is how to generate jsonSchema used for generating HTML5 GUI using json-editor:

    val objectMapper = new ObjectMapper
    val jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper, config = JsonSchemaConfig.html5EnabledSchema)
    val jsonSchema:JsonNode = jsonSchemaGenerator.generateJsonSchema(classOf[YourPOJO])
    
    val jsonSchemaAsString:String = objectMapper.writeValueAsString(jsonSchema)

This is how to generate jsonSchema using custom type-to-format-mapping using Scala:

    val objectMapper = new ObjectMapper
    val config:JsonSchemaConfig = JsonSchemaConfig.vanillaJsonSchemaDraft4.copy(
      customType2FormatMapping = Map( "java.time.OffsetDateTime" -> "date-time-ABC-Special" )
    )
    val jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper, config = config)
    val jsonSchema:JsonNode = jsonSchemaGenerator.generateJsonSchema(classOf[YourPOJO])
    
    val jsonSchemaAsString:String = objectMapper.writeValueAsString(jsonSchema)

Note about Scala and Option[Int]:

Due to Java's Type Erasure it impossible to resolve the type T behind Option[T] when T is Int, Boolean, Double. Ass a workaround, you have to use the @JsonDeserialize-annotation in such cases. See https://github.com/FasterXML/jackson-module-scala/wiki/FAQ#deserializing-optionint-and-other-primitive-challenges for more info.

Example:

    case class PojoUsingOptionScala(
                                     _string:Option[String], // @JsonDeserialize not needed here
                                     @JsonDeserialize(contentAs = classOf[Int])     _integer:Option[Int],
                                     @JsonDeserialize(contentAs = classOf[Boolean]) _boolean:Option[Boolean],
                                     @JsonDeserialize(contentAs = classOf[Double])  _double:Option[Double],
                                     child1:Option[SomeOtherPojo] // @JsonDeserialize not needed here
                                   )

PS: Scala Option combined with Polymorphism does not work in jackson-scala-module and therefor not this project either.

Code - Using Java

    ObjectMapper objectMapper = new ObjectMapper();
    JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper);
    
    // If using JsonSchema to generate HTML5 GUI:
    // JsonSchemaGenerator html5 = new JsonSchemaGenerator(objectMapper, JsonSchemaConfig.html5EnabledSchema() );
    
    // If you want to confioure it manually:
    // JsonSchemaConfig config = JsonSchemaConfig.create(...);
    // JsonSchemaGenerator generator = new JsonSchemaGenerator(objectMapper, config);
               
    
    JsonNode jsonSchema = jsonSchemaGenerator.generateJsonSchema(YourPOJO.class);
    
    String jsonSchemaAsString = objectMapper.writeValueAsString(jsonSchema);

Backstory

At work we've been using the original jackson-module-jsonSchema to generate schemas used when rendering dynamic GUI using https://github.com/jdorn/json-editor.

Recently we needed to support POJO's using polymorphism like this:

    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = Child1.class, name = "child1"),
            @JsonSubTypes.Type(value = Child2.class, name = "child2") })
    public abstract class Parent {
    
        public String parentString;
        
    }

This is not supported by the original jackson-module-jsonSchema. I have spent many hours trying to figure out how to modify/improve it without any luck, and since it is implemented in such a complicated way, I decided to instead write my own jsonSchema generator from scratch.

About

Generate JSON Schema draft 4 with Polymorphism using Jackson annotations

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Scala 71.9%
  • Java 28.1%