-
-
Save 573/bf175fbbec6404c235628b55480056bf to your computer and use it in GitHub Desktop.
Jackson 2.5+ sample code for generating JSON schemas that always use schema references instead of inline schemas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.therapi.apidoc; | |
import java.util.List; | |
import com.fasterxml.jackson.databind.JavaType; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.module.jsonSchema.JsonSchema; | |
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; | |
import com.fasterxml.jackson.module.jsonSchema.factories.VisitorContext; | |
public class JsonSchemaExample { | |
/** | |
* Treat all schemas as "seen" so that model schemas are never inlined. | |
*/ | |
public static class VisitorContextWithoutSchemaInlining extends VisitorContext { | |
@Override | |
public String addSeenSchemaUri(JavaType aSeenSchema) { | |
return getSeenSchemaUri(aSeenSchema); | |
} | |
@Override | |
public String getSeenSchemaUri(JavaType aSeenSchema) { | |
return isModel(aSeenSchema) ? javaTypeToUrn(aSeenSchema) : null; | |
} | |
protected boolean isModel(JavaType type) { | |
return type.getRawClass() != String.class | |
&& !isBoxedPrimitive(type) | |
&& !type.isPrimitive() | |
&& !type.isMapLikeType() | |
&& !type.isCollectionLikeType(); | |
} | |
protected static boolean isBoxedPrimitive(JavaType type) { | |
return type.getRawClass() == Boolean.class | |
|| type.getRawClass() == Byte.class | |
|| type.getRawClass() == Long.class | |
|| type.getRawClass() == Integer.class | |
|| type.getRawClass() == Short.class | |
|| type.getRawClass() == Float.class | |
|| type.getRawClass() == Double.class; | |
} | |
} | |
public static class Animal { | |
public String species; | |
} | |
public static class Zoo { | |
public String name; | |
public List<Animal> animals; | |
} | |
public static void main(String[] args) throws Exception { | |
ObjectMapper m = new ObjectMapper(); | |
Class generateSchemaFor = Zoo.class; | |
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); | |
visitor.setVisitorContext(new VisitorContextWithoutSchemaInlining()); | |
m.acceptJsonFormatVisitor(m.constructType(generateSchemaFor), visitor); | |
JsonSchema jsonSchema = visitor.finalSchema(); | |
System.out.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment