Code Monkey home page Code Monkey logo

jsonschema-generator's Introduction

Java JSON Schema Generator

Build Status Maven Central

Creating JSON Schema (Draft 6, Draft 7, Draft 2019-09 or Draft 2020-12) from your Java classes utilising Jackson.


This project consists of:

  • the victools/jsonschema-generator (the only thing you need to get started)
  • a few modules bundling standard configurations for your convenience:
    • victools/jsonschema-module-jackson – deriving JSON Schema attributes from jackson annotations (e.g. "description", property name overrides, what properties to ignore) as well as looking up appropriate (annotated) subtypes
    • victools/jsonschema-module-jakarta-validation – deriving JSON Schema attributes from jakarta.validation.constraints annotations (e.g. which properties are nullable or not, their "minimum"/"maximum", "minItems"/"maxItems", "minLength"/"maxLength")
    • victools/jsonschema-module-javax-validation – deriving JSON Schema attributes from javax.validation annotations (e.g. which properties are nullable or not, their "minimum"/"maximum", "minItems"/"maxItems", "minLength"/"maxLength")
    • victools/jsonschema-module-swagger-1.5 – deriving JSON Schema attributes from swagger (1.5.x) annotations (e.g. "description", property name overrides, what properties to ignore, their "minimum"/"maximum", "const"/"enum")
    • victools/jsonschema-module-swagger-2 – deriving JSON Schema attributes from swagger (2.x) @Schema annotations
  • the victools/jsonschema-maven-plugin – allowing you to generate JSON Schemas as part of your Maven build

Another example for such a module is:


Documentation

JavaDoc is being used throughout the codebase, offering contextual information in your respective IDE or being available online through services like javadoc.io.

Additional documentation and configuration examples can be found here: https://victools.github.io/jsonschema-generator


Usage

Dependency (Maven)

<dependency>
    <groupId>com.github.victools</groupId>
    <artifactId>jsonschema-generator</artifactId>
    <version>4.35.0</version>
</dependency>

Since version 4.7, the release versions of the main generator library and the (standard) victools modules listed above are aligned. It is recommended to use identical versions for all of them to ensure compatibility.

It is discouraged to use an older/lower jsonschema-generator version than any of your jsonschema-module-* dependencies. If the module uses any feature only added to the jsonschema-generator in the newer version, runtime errors are to be expected.

Code

Complete/Minimal Example

import com.fasterxml.jackson.databind.JsonNode;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode jsonSchema = generator.generateSchema(YourClass.class);

System.out.println(jsonSchema.toPrettyString());

Additional examples can be found in the jsonschema-examples folder or throughout the various tests classes.

jsonschema-generator's People

Contributors

carstenwickner avatar dependabot[bot] avatar eimanip avatar emmeral avatar gaetanopiazzolla avatar hashar avatar imifou avatar janlabrie avatar jeff-miller-cfa avatar magicdgs avatar nephery avatar snyk-bot avatar takanuva15 avatar tarilabs avatar vlaxos713 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonschema-generator's Issues

NoSuchMethodError with 4.4.0

Following error occurs while using 4.4.0:

java.lang.NoSuchMethodError: com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder.forTypesInGeneral()Lcom/github/victools/jsonschema/generator/SchemaGeneratorTypeConfigPart;

Problem doesn't occur with 4.3.0.

Environment:

  • Java 11

Code:

public void createSchema(final Class clazz, final Writer target) throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writerWithDefaultPrettyPrinter();
    final var configBuilder = new SchemaGeneratorConfigBuilder(objectMapper, OptionPreset.PLAIN_JSON);
    final var config = configBuilder.with(Option.NONPUBLIC_NONSTATIC_FIELDS_WITHOUT_GETTERS)
                                    .with(new JacksonModule())
                                    .with(new JavaxValidationModule(INCLUDE_PATTERN_EXPRESSIONS, NOT_NULLABLE_FIELD_IS_REQUIRED))
                                    .build();
    final var generator = new com.github.victools.jsonschema.generator.SchemaGenerator(config);
    final var jsonSchema = generator.generateSchema(clazz);

    target.write(jsonSchema.toPrettyString());
    target.flush();
}

Maven dependency:

<dependency>
    <groupId>com.github.victools</groupId>
    <artifactId>jsonschema-generator</artifactId>
    <version>[4.0.0,5.0.0)</version>
</dependency>
<dependency>
    <groupId>com.github.victools</groupId>
    <artifactId>jsonschema-module-javax-validation</artifactId>
    <version>[4.0.0,5.0.0)</version>
</dependency>
<dependency>
    <groupId>com.github.victools</groupId>
    <artifactId>jsonschema-module-jackson</artifactId>
    <version>[4.0.0,5.0.0)</version>
</dependency>

FasterXML Jackson is 2.10.2.

Javax Validation Module: Validating Container Elements

Hello. Great project so far. However, I've been running into an issue trying to apply container element constraints using the Javax validation module. For instance, I want to do something like: List<@Size(max=3) String> countryCodes but I can't get the result to appear in the schema output. Is there a configuration I need to do? Is it already an included feature? Thanks!

Use Jackson annotations for enum values

From the discussion in #25

There can be cases where an enum uses a toString() method representation, and a different format for the serialisation to json.
When using Jackson, the latter method is annotated with @JsonValue to instruct Jackson to us that implementation for JSON serialisation.

Currently the library allows using the name value, or the toString() value (with the new FLATTENED_ENUMS_FROM_TOSTRING option), but the Jackson module doesn't correctly use the annotated method to serialise in the schema. This means that the generated schema has different enum values to the json generated.

Is there a way to make use of the JsonValue annotation when generating the schema to keep both in sync?

Support subtype look-up per field/method

GH-24 introduced the ability to determine specific subtypes of an encountered type in order to list them explicitly (via anyOf).

However, sometimes there are very generic type declarations which by convention are only ever populated with a few specific subtypes even though there are technically more.
Some libraries (like Jackson) cater for the specific declaration of subtypes on a per-type basis as well as on a property (field/method) basis.

  • The Schema Generator should allow for this per-property look-up of eligible subtypes, which should override the more general per-type look-up, e.g. when encountering an Animal supertype that has various implementations (such as Dog, Cat, Elephant, Boar) on a field called "pet", maybe only Dog and Cat are eligible subtypes – hopefully, indicated in the code somehow. (#48 and released in v4.7.0)

  • Additionally, the jackson module could be enhanced to consider the @JsonSubTypes annotation. (#55 + #58 and released in v4.8.0)

@JsonNaming Annotation Ignored

I have a class like this:

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class MyObject {
    private String s3Path;
}

Because of the JsonNaming annotation, the field will be returned as s3_path but the generated schema will generate it as s3Path so when receiving the object on the other end it fails because it expects s3Path but receives s3_path in the JSON payload.

It would be great if this annotation could be supported and the naming adjusted as specified by the case to avoid mismatches.

Can you release jsonschema-module-jackson 4.7.0?

Apologies for opening this issue here, but issues are not enabled for jsonschema-module-jackson.

It would be very convenient to have a unified release version for all your jsonschema components, and it looks like you are at least partially doing that for jsonschema-module-javax-validation like:

image

Can you release a 4.7.0 Compatibility Declaration for jsonschema-module-jackson also? Thanks!

NoSuchMethodError in Release 4.5.0

Hi,

again a NoSuchMethodError which breaks our nightly build with version range.


[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.071 s <<< FAILURE! - in schema.SchemaExportTest
369 20832 [ERROR] print Time elapsed: 1.071 s <<< ERROR!
370 java.lang.NoSuchMethodError: com.github.victools.jsonschema.module.jackson.JacksonModule: method ()V not found
371 at schema.SchemaExportTest.lambda$print$0(SchemaExportTest.java:48)
372 at schema.SchemaExportTest.print(SchemaExportTest.java:35)


Code:

    public void createSchema(final Class clazz, final Writer target) throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writerWithDefaultPrettyPrinter();
        final var configBuilder = new SchemaGeneratorConfigBuilder(objectMapper, OptionPreset.PLAIN_JSON);
        final var config = configBuilder.with(Option.NONPUBLIC_NONSTATIC_FIELDS_WITHOUT_GETTERS)
                                        .with(new JacksonModule())
                                        .with(new JavaxValidationModule(INCLUDE_PATTERN_EXPRESSIONS, NOT_NULLABLE_FIELD_IS_REQUIRED))
                                        .build();
        final var generator = new com.github.victools.jsonschema.generator.SchemaGenerator(config);
        final var jsonSchema = generator.generateSchema(clazz);

        target.write(jsonSchema.toPrettyString());
        target.flush();
    }

Runtime: Java 11

Conditional schema generation.

Hello,

Could you please let me know as how we can generate the conditional schema as mentioned in here - https://json-schema.org/understanding-json-schema/reference/conditionals.html

I need something like below with which I can validate with only given schema type.

 "allOf": [
    {
      "if": {
        "properties": {
          "type": {
            "const": "scheme2"
          }
        }
      },
      "then": {
        "$ref": "#/definitions/scheme2"
      }
    },
    {
      "if": {
        "properties": {
          "type": {
            "const": "scheme1"
          }
        }
      },
      "then": {
        "$ref": "#/definitions/scheme1"
      }
    }
  ]

Object class not defined when specified as part of a Map.

I'm trying to generate a schema based on the following class:

package mypackage;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class Response {
    @JsonProperty("collection")
    Collection collection;

    @JsonProperty("results")
    Map<String, Result> results;

    @JsonProperty("total_hits")
    int totalHits;
}

using the following configuration:

SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder
        .with(Option.DEFINITIONS_FOR_ALL_OBJECTS)
        .build();
SchemaGenerator generator = new SchemaGenerator(config);

and the result is:

{
  "$schema" : "http://json-schema.org/draft-07/schema#",
  "definitions" : {
    "Collection" : {
      "type" : "string",
      "enum" : [ "A", "B" ]
    },
    "Map(String,Result)" : {
      "type" : "object"
    }
  },
  "type" : "object",
  "properties" : {
    "collection" : {
      "$ref" : "#/definitions/Collection"
    },
    "results" : {
      "$ref" : "#/definitions/Map(String,Result)"
    },
    "totalHits" : {
      "type" : "integer"
    }
  }
}

As you can see, the Result object (which contains 2 strings) is not being detailed even though I specified DEFINITIONS_FOR_ALL_OBJECTS. I've tried specifying a Result variable in the Response class and that generates a Result definition but it's still not mapped into the definition for Map(String,Result).

Maven plugin - Configuration of the generator

The configuration of a Generator in the pom.xml should support :

  • Base definition: One of the labels of OptionPreset. PLAIN_JSON as the default value.
  • Options that have to be enabled
  • Options that have to be disabled

Classpath of the maven plugin is not properly set

Testing the Maven plugin with the unit tests works fine. But...testing it in my real-live project revealed that the removal of the explicit classpath setting and usage of the @requiresDependencyResolution annotation is not good enough.

Error loading class ... is the consequence.

When you read the quote from The Maven Guide

Please note that the plugin classloader does neither contain the dependencies of the current project nor its build output. Instead, plugins can query the project's compile, runtime and test class path from the MavenProject in combination with the mojo annotation requiresDependencyResolution from the Mojo API Specification. For instance, flagging a mojo with @requiresDependencyResolution runtime enables it to query the runtime class path of the current project from which it could create further classloaders.

you see that the requiresDependencyResolution does not add the dependencies to the classpath. This is what you need to do yourself.

I will create a branch to fix this.

Add Option "ENUM_FROM_TO_STRING"

Hi all,
first of all, would like to thank you for the awesome job you are doing.
It would be great to add the Option like "ENUM_FROM_TO_STRING".
Currently, the schema is generated from the enum's name() method and it looks like
"enum" : ["FIRST", "SECOND", "THIRD"], but the actual API response could contain values from toString() like ["First", "Second", "Third"]. (This is what I am experiencing right now on my current project)

It could be a separate Module like EnumFromToStringModule with a method looks like this or better :)

private static <E extends Enum<E>> List<String> extractEnumValuesFromToString(ResolvedType enumType) {
    Object[] enumConstants = enumType.getErasedType().getEnumConstants();
    List<String> resolvedEnumValues = new ArrayList<>();
    for (Object enumConstant : enumConstants) {
        Class<?> enumClass = enumConstant.getClass();
        try {
            Method toStringMethod = enumClass.getDeclaredMethod("toString");
            String enumValue = (String) toStringMethod.invoke(enumConstant);
            resolvedEnumValues.add(enumValue);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
    return resolvedEnumValues;
}

Allow for integration in OpenAPI 3.1

The motivation for this enhancement is this great blog post from Phil Sturgeon, describing how OpenAPI has been a subset and a superset of JSON Schema at the same time (i.e. only parts of the JSON Schema keywords were supported, while additional ones were added on top).

With the upcoming OpenAPI version 3.1, this is supposed to change insofar as that it will be only a superset of JSON Schema Draft 2019-09 (i.e. supporting all its keywords, but adding some more on top of it).
He also advocates for the API-first approach, but that is mostly applicable to new projects and not to (big) existing ones that would've to undergo extensive (manual) refactoring to produce an appropriate OpenAPI description out of the existing codebase that doesn't have the relatively new @OpenApi annotations everywhere.

Goal

The overall goal here would be to allow for the flexible generation of an OpenAPI definition from a codebase that has little to no @OpenAPI annotations on it yet. Based on that, the existing codebase could then be automatically replaced/regenerated from the OpenAPI definition. Et voilá: welcome in the API-first world. From here on out, you can make changes directly in the OpenAPI definition and have those reflected in your code.

The migration complexity would then lie in the configuration of the jsonschema-generator to pick-up as much accurate information as possible and include it in the generated models/schemas in the OpenAPI definition to minimize the information loss. The jsonschema-generator would then only be a one-time migration tool – assuming you don't need a separate generation of JSON Schemas besides what is included in the OpenAPI definition then.

What to do?

First steps: jsonschema-generator enhancements

  • Allow for the schema generation in the context of the OpenAPI format.
    • Allow for multiple entry/main types to be provided one-after-the-other and only in the very end producing a common list of definitions/$defs. #84
    • Allow for an alias for $defs to be provided, i.e. to allow for "$ref": "#/components/schemas/YourType" instead of the currently unchangeable "$ref": "#/$defs/YourType". #84
    • Apply stricter naming rules for definition keys. #84
    • Cater for additional OpenAPI attributes (like "format": "int32") to be set via standard option. #136
    • Create a new jsonschema-module-swagger-2 to pick-up model/schema related information provided via the respective OpenAPI @Schema annotations (for those cases, where parts of the codebase already have them or where a separate JSON Schema is being generated). #117

Next steps: integrate with OpenAPI definition being generated (e.g. by swagger-core)

  • Once all the above is done, find a way to hook into the latest swagger-core (which by then hopefully supports OpenAPI 3.1 already – right now it is still OpenAPI 3.0, based on JSON Schema Draft 4):
    • Provide a swagger ModelConverter implementation, that uses a given victools SchemaGeneratorConfig instance.
  • Alternatively (if the above is too difficult/cumbersome):
    • Accept a normally produced swagger definition as input and replace the contained models/schemas, assuming there is a way to unambiguously identify the classes that Swagger had encountered in the first place.

Contributions

This is just a rough plan. I'm open to suggestions and would certainly appreciate help along the way. I feel comfortable doing the "first steps" (hoping that those would be enough), but completing the "next steps" (or whatever else would be required to achieve the overall "goal") will likely exceed the time I can dedicate to this in the next couple of months.
Since OpenAPI 3.1 has not been released yet and swagger-core may also need adjustments first to support it, there doesn't seem to be any rush. For OpenAPI 3.0 it may not be worth it to invest the time necessary to workaround the larger number of differences.

Javax validation support for groups

Hi, it would be nice, to generate schema as follows

ObjectMapper objectMapper = new ObjectMapper();
JavaxValidationModule module = new JavaxValidationModule(group1, group2);
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(objectMapper, OptionPreset.PLAIN_JSON)
        .with(module);
SchemaGeneratorConfig config = configBuilder.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode jsonSchema = generator.generateSchema(Yourclass.class);

Support dynamic addition of properties

GH-45 aims at considering the Jackson @JsonSubTypes annotation for looking-up per-property subtypes. In that context, Jackson also has a @JsonTypeInfo annotation which may describe an identifier (e.g. a "type" property) how the subtypes may be differentiated.

In some cases, this additional identifier may not already be declared as such but could potentially be added automatically during serialization to JSON.

The Schema Generator should cater for this kind of identifier (property) being added without having a declared field/method as reference for it.

Additionally, the jackson module could be enhanced to consider the @JsonTypeInfo annotation accordingly: (1) adding this kind of identifier property as per the @JsonTypeInfo annotation and (2) ideally setting its "const" value as per the @JsonSubTypes annotation.

Keep original order of JSON properties

Hi,

in my project I need to keep the original order of JSON properties.
In "SchemaGenerationContextImpl.generateObjectDefinition (ResolvedType, ObjectNode)" the 2 lines

final Map<String, JsonNode> targetFields = new TreeMap<>();
final Map<String, JsonNode> targetMethods = new TreeMap<>();

could be replaced by something like this:

final Map<String, JsonNode> targetFields;
final Map<String, JsonNode> targetMethods;
if (this.generatorConfig.shouldKeepOriginalPropertiesOrder()) {
    targetFields = new LinkedHashMap<>();
    targetMethods = new LinkedHashMap<>();
} else {
    targetFields = new TreeMap<>();
    targetMethods = new TreeMap<>();
}

with the new method shouldKeepOriginalPropertiesOrder() and a new appropriate option.

Is it possible?

Best regards
Udo

How to create json schema consisting of inclusive forbidden fields ?

Hi,

I am not sure how to generate schema for the following condition. Could you please help.
I have following class:

Class Job{
   private CASTE caste;
   private String reservationPercent;
   private String ageRelaxation;
}

Where the ENUM case is defined as

enum CASTE{
OBC,
GENERAL,
SC_ST;
}

I want to convey in my schema that "reservationPercent" and "ageRelaxtion" field should not be in the schema (inclusive forbidden) if CASTE is GENERAL.
I dont know even if its possible via anyOf or oneOf.

Could you please help, if you have idea about it.

How to access "parent's" field that holds the reference to the current field

Sorry, I have to ask another question. That's what you get for being so helpful. ;-)
I'm trying to write a module that consumes Swagger v3 annotations.
I have the following class structure (more or less)

interface IReference {
  String getName();
}

class Reference<T> extends IReference {

}
@Schema(description= "the foo's person")
interface PersonReference extends IReference {
  @Schema(description = "the person's name")
  String getName();
}

class Foo {
  @Schema(implementation = PersonReference.class)
  private Reference<Person> person;
}

In my module, I want to resolve the description for Foo.person.name, but in the description resolver, I only get a reference to the name field in the Reference class. I somehow need to resolve the @Schema#implementation() from there but I can't seem to access the Foo.person field from there.

class MyModule {
  .... 
  fieldConfigPart.withDescriptionResolver(member -> {
    // member is the "name" field in Reference which does not have a @Schema annotation
    // how can I access the "name" field from PersonReference here?
    // I can only move up to Reference<Person> via member.getDeclaringType
  }
}

Does that make sense?

Maven plugin

Hello

This project looks excellent! Really good to see support for Bean validation.

Is there a maven plugin, that will allow schema generation using maven, eg mvn generate source?

Backward compatibility problem with "jsonschema-generator-parent"

In case the dependency declaration in Maven is

<dependency>
    <groupId>com.github.victools</groupId>
    <artifactId>jsonschema-generator</artifactId>
    <version>[4.4.0,5.0.0)</version>
</dependency>

build will fail with message that dependency "jsonschema-generator-parent" version 4.8.0 can't be resolved. Even if 4.8.1 is available.

Workaround: set version to [4.8.1.0,5.0.0).

Ignoring minItems constraint while building json schema

I tried to build json schema using jsonschema-module-javax-validation module and found that minItems constraint is ignored. Also i found that jsonschema-module-javax-validation module works as expected and com.github.victools.jsonschema.generator.impl.AttributeCollector builds node with expected constraints, but com.github.victools.jsonschema.generator.SchemaGenerator ignores them.

May be i have erroneous configuration)
json-schema

Property with @JsonIgnore is excluded even though there is a getter with @JsonProperty

I have a bean class that looks like this:

public class TestDto {

    @JsonIgnore
    private String name;

    @JsonProperty("name")
    public String getTheName() {
        return name;
    }
}

The generated schema does not include the name property. It gets filtered out by JacksonModule.shouldIgnoreField(FieldScope) where it says

        // other kinds of field ignorals are handled implicitly, i.e. are only available by way of being absent
        return beanDescription.findProperties().stream()
                .noneMatch(propertyDefinition -> fieldName.equals(propertyDefinition.getInternalName()));

Should we really use getInternalName() there instead of getName()?

Maven plugin - Do we want to support a default configuration?

Currently the Maven plugin has a default configuration which consist of all known Modules from the jsonschema-generator project.

When this configuration is usefull to a large part of the user group we should keep it. Else we should remove it, because it would require all Modules to be on the Maven dependency list.

@carsten: I believe you are in favor of removing the default configuration right?

How to disable definition for ENUMS

Hi,

I am configuring schema generator with following option "with(Option.DEFINITIONS_FOR_ALL_OBJECTS)" but its adding definition for ENUMS as well. For e.g.:

{
   "$schema":"https://json-schema.org/draft/2019-09/schema",
   "$defs":{
      "Department":{
         "type":"object",
         "properties":{
            "departmentName":{
               "type":"string",
               "default":"Science"
            }
         },
         "additionalProperties":false
      },
      "StudentUniform":{
         "type":"string",
         "enum":[
            "GREY",
            "WHITE"
         ]
      }
   },
   "type":"object",
   "properties":{
     
      "department123":{
         "$ref":"#/$defs/Department"
      },

      "uniform":{
         "$ref":"#/$defs/StudentUniform"
      }
   },
   "additionalProperties":false
}

Could you please tell how could I disable it for ENUM. Could you also please tell if I can change the order so that actual object definition appears at the end.

Is it possible to overwrite a type by another?

I have some AVRO generated classes that I need to get JSON schema for. These classes use org.apache.avro.util.Utf8 class in place of String.

Is it possible to overwrite org.apache.avro.util.Utf8 to become string in schema?

Support Draft 2019-09

A new draft 8 (or now officially: "2019-09") has been published and there appear to be only two relevant changes for the schema generation before being able to claim compatibility:

  • new $schema value ("https://json-schema.org/draft/2019-09/schema") #44
  • definitions is now $defs (definitions is still allowed for compatibility reasons, but deprecated) #44

One other interesting change is the following one, which would allow for less allOf wrappers being necessary but is only a nice-to-have (as it complicates the handling of these things):

  • $ref – Other keywords are now allowed alongside it #47

Everything else is either related to the schema validation, hyper schemas, or elements of the core schema that are currently not being used here.

Refer to https://json-schema.org/draft/2019-09/release-notes.html for details.

Full inlined schema support

Hello, first would like to say that you did an amazing job with this library.

I am using your library at Fedex, and we have a use case that may seem not very usual, but nonetheless a interesting functionality to support, and apparently simple.

We need the generated schema to be fully inlined, this means, never user a $ref.

The reason is that we add dynamic rules on top of the static rules generated for the class, making really hard to do "allOf" compositions when a reference have another reference inside. A example would be the address class that each country have different postal code pattern. So, sender and receiver fields might have different validation rules for the same class.

Also the front end "walks" the schema, retrieving enum values and required fields to setup the UI.

We generate all the json schema by hand, but we want to use your library and just add the dynamic rules by hand.

I will fork your library and start working on it. Please let me know if you have any suggestion of how to accomplish it, and if you are ok with me opening a PR soon.

Kind Regards,
Octavio.

Configuring schema with exclusive maxima/minima producing incorrect schema

Hi,

I am configuring schema as follow to use exclusive maximum:

configBuilder.forFields().withNumberExclusiveMaximumResolver(field ->
 {
           Max annotation = field.getAnnotationConsideringFieldAndGetter(Max.class);
          return annotation != null ? new BigDecimal(annotation.value()) : null;
});

However I am getting ("exclusiveMaximum":1E+1) in my schema instead of actual value (which is 10). The annotation MAX returning long type value. I also tried with hardcoded value "10l" but got same result.

Could you please help.

Thanks,
Tarun

Add "additionalProperties" : false to objects by default

It would be useful to add "additionalProperties" : false for objects ("type" : "object") because by default additionalProperties is true and it means, that this object can contain other fields. But if the source of the schema is Java files, it's impossible to have other fields.

Currently I use such a code as workaround:

private static final String TAG_ADDITIONAL_PROPERTIES = "additionalProperties";

.with((jsonSchemaTypeNode, scope, config) -> {
	JsonNode type = jsonSchemaTypeNode.get(TAG_TYPE);
	if (type != null && type.isTextual() && type.textValue().equals(TAG_TYPE_OBJECT)) {
		if (jsonSchemaTypeNode.has(TAG_PROPERTIES)) {
			jsonSchemaTypeNode.put(TAG_ADDITIONAL_PROPERTIES, false);
		}
	}
})

Or, as an option, have it configurable using Option.

Javax validations support list elements

Hi, test below do not return constraint description for ListElement values.

    @Test
    public void test() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaxValidationModule module = new JavaxValidationModule();
        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(objectMapper, OptionPreset.PLAIN_JSON)
                .with(module);
        SchemaGeneratorConfig config = configBuilder.build();
        SchemaGenerator generator = new SchemaGenerator(config);
        JsonNode jsonSchema = generator.generateSchema(RootForm.class);

        System.out.println(jsonSchema.toString());
    }

    private static class RootForm {
        @NotEmpty
        private String name;
        @Valid
        private ChildForm childForm;
    }

    private static class ChildForm {
        @Valid
        private List<ListElement> elements;
        @Min(2)
        private Integer count;
    }

    private static class ListElement {
        @NotNull
        private String value;
    }

Support for @JsonProperty in enums

Support for @JsonProperty is offered for regular fields, but not for enumerations - currently, we have to use @JsonValue if we want to control the schema generation of the constants:

public enum TestEnum {
    A("a"),
    B("b");

    private String value;

    TestEnum(String value) {
        this.value = value;
    }

    @JsonValue
    public String getValue() {
        return value;
    }
}

Would it be possible to add support for @JsonProperty instead please? This would cut down on the amount of boilerplate needed:

public enum TestEnum {
    @JsonProperty("a")
    A,
    @JsonProperty("b")
    B
}

Thanks!

(Also wanted to mention that this library rocks - this is the first one I've found that handles @JsonTypeInfo correctly!)

Generate allof tag.

Hi,

Using withtypesingeneral() , I can generate schema with anyOf tag.
I would like to know how I can have allOf tag instead.

Support for @JsonIdentityReference and @JsonIdentityInfo

When a member of a Java class is annotated with @JsonIdentityReference, Jackson will serialize it as a reference to another object, instead of the full nested object. The reference is derived from the @JsonIdentifyInfo annotation on the referenced class.

Examples and Javadoc is found here and here

The current schema generator does not take that into account.

I would be good when the generator will recognize the @JsonIdentifyReference in the Jackson module and generate the type information of the id of the references object instead of the object itself.

In my project I made an implementation of this. I will prepare a PR for it, so you can form an opinion.

Allow for multiple overridden types at once

There is already a way to override a given property's type by way of:

  • SchemaGeneratorConfigPart.withTargetTypeOverrideResolver()

However, that only allows for one-to-one replacements -- e.g. replacing all occurrences of an interface with a single implementation that may contain more/different properties.

But what about those cases, where an interface is implemented by multiple types -- e.g. a Pet being either a Cat or a Dog?

The generator (and its configuration) should therefore be extended to:

  1. allow for (multiple) subtypes to be identified,
  2. in case of multiple of those subtypes, they should be included separately via anyOf (since oneOf would require them to be mutually exclusive).

Wiki example is out of date

The following wiki https://github.com/victools/jsonschema-generator/wiki#143-target-type-overrides example is not compiling:

configBuilder.forFields().withTargetTypeOverridesResolver(field -> {
        if (field.getDeclaringType().getErasedType() == ExampleForTargetTypeOverrides.class
                && field.getName().equals("value")) {
            return Stream.of(String.class, Number.class)
                    .map(specificSubtype -> field.getContext().resolveType(specificSubtype))
                    .collect(Collectors.toList());
        }
        return null;
    });

It'd be great to update this example with a working solution.

Thanks

Support for ordering of properties

Hi,

What I have noticed so far that generated schema list properties in alphabetical order. Is it possible to tell schema generator to list properties in the same order it is listed in the source code ?

Thanks for your support.

How to add condition in JSON Schema

Hi,

First of all. thank you for providing great api to work with for JSON Schema.
I am actually to trying to define condition in JSON Schema.
Lets say if have a following class:

class Student {
    private DressColor dressColor; //DressColor is ENUM
    private int fineApplicable;
}

I want my json schema to have following condition:

  • If dressColor is "GREY", fineApplicable field should be required.

There are similar examples on stackoverflow as well:
https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required

Could you please how we can add these conditions in JSON schema using the library.

Thanks,
Tarun

Scanner SubTypesScanner was not configured

Hey,
first of all your jsonschema-generator is really great thing!
I love it!

I am jusing maven to generate json schemas out of my Pojo classes.
this works like a charm when using it like this:

<classNames>
    <className>model.entity.user.User</className>
    <className>model.entity.group.Group</className>
</classNames>

if i want to use it like this:

<packageNames>
    <packageName>mode</packageName>
</packageNames>

i get an exception from

org.reflections

Caused by: org.reflections.ReflectionsException: Scanner SubTypesScanner was not configured

Can you explain how to configure the SubTypesScanner via maven?
Regards and Dankeschön
Clem

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.