mbknor / mbknor-jackson-jsonSchema

Generate JSON Schema with Polymorphism using Jackson annotations
MIT License
232 stars 75 forks source link

How to allow additionalProperties ? #140

Closed azakordonets closed 3 years ago

azakordonets commented 3 years ago

I'm trying to use your library to generate JSON schema's and so far it works great - thanks for the lib. I have one problem that i can't figure out - i would like to allow additionalProperties in my schema, but disabling FAIL_ON_UNKNOWN_PROPERTIES option in ObjectMapper doesn't help :

public static JSONObject generateJsonSchema(Class clazz) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper);
        JsonNode jsonSchema = jsonSchemaGenerator.generateJsonSchema(clazz);
        String json = mapper.writeValueAsString(jsonSchema);
        return new JSONObject(json);
    }

Results in

"headers" : {
    "$schema" : "http://json-schema.org/draft-04/schema#",
    "additionalProperties" : false,
    "title" : "Headers",
    "type" : "object",
    "properties" : {
      "x-request-trace-id" : {
        "type" : "string"
      },
      "content-type" : {
        "pattern" : "^application\\/json",
        "type" : "string"
      }
    },
    "required" : [ "content-type", "x-request-trace-id" ]
  }

Example of pojo:

@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Headers {
    @JsonProperty(value = "content-type", required = true)
    @Pattern(
            regexp = "^application\\/json"
    )
    private String contentType;
    @JsonProperty(value = "x-request-trace-id", required = true)
    private String traceId;
    @Pattern(
            regexp = "Bearer [a-zA-Z-0-9]{60}"
    )
    private String authorization;
    @Pattern(
            regexp = "^application\\/json"
    )
    private String accept;
}
azakordonets commented 3 years ago

I managed to find a solution :

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);
    }

Again, thanks a lot for a great library 🙇‍♂️👍