in jackson json schema java ~ read.

Generating JSON Schema in Java with "additionalProperties" set to "true"

Recently i was working on a new tool for contract testing that we decided to develop in New10 from scratch. We decided that we would like to use JSON Schema's for contracts validation and for that i needed to implement several SDK's in typescript, java, python in order to support all the services we have. While working on Java SDK, i faced a problem with JSON schema generation for some of our models. At first i was using jackson-module-jsonSchema library, where i faced with one major problem - i couldn't generate "required": [] attribute because of this issue
So, instead, i found another library that was working better for me. But with it i faced with another problem - by default it was setting additionalProperties: true for every class, which is a bummer for me. Luckily i managed to find some hints in the documentation and code that allowed me to bypass this situation and now i would like to share it with everyone ( and myself in the future) :

public static JSONObject generateJsonSchema(Class clazz) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonSchemaConfig config = JsonSchemaConfig.vanillaJsonSchemaDraft4().withFailOnUnknownProperties(false);
        config = config.withFailOnUnknownProperties(false);
        JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper, config);
        JsonNode jsonSchema = jsonSchemaGenerator.generateJsonSchema(clazz);
        String json = mapper.writeValueAsString(jsonSchema);
        return new JSONObject(json);
    }

That's pretty much everything you need in order to generate a JSON Schema out of a Java class.

Hope it help someone besides me :)

Happy coding everyone.

comments powered by Disqus
comments powered by Disqus