reinert / JJSchema

A generator from Java Types to JSON-Schema using Jackson.
Other
117 stars 56 forks source link

Enum null values should be null primitive instead of string #84

Closed reinert closed 6 years ago

reinert commented 6 years ago

Currently enums accepting null values get a "null" string into their accepted values, but it should be null primitives.

Related to #81 .

can-staxter commented 5 years ago

Hello, Here https://github.com/reinert/JJSchema/blob/master/src/main/java/com/github/reinert/jjschema/JsonSchemaGenerator.java on line 413: // Check if the Nullable annotation is present, and if so, add 'null' to type attr Nullable nullable = propertyReflection.getAnnotation(Nullable.class); if (nullable != null) { if (returnType.isEnum()) { ((ArrayNode) schema.get("enum")).add("null"); } else { String oldType = schema.get(TAG_TYPE).asText(); ArrayNode typeArray = schema.putArray(TAG_TYPE); typeArray.add(oldType); typeArray.add("null"); } }

when a field of POJO is a nullable enum, it only adds its value to the created schema.

For example: for this field: @Nullable @JsonProperty( "booking-status" ) private BookingStatus bookingStatus;

When we do this: com.github.reinert.jjschema.v1.JsonSchemaFactory schemaFactory = new JsonSchemaV4Factory(); schemaFactory.setAutoPutDollarSchema( true ); JsonNode schema = schemaFactory.createSchema( clazz );

It adds this to the schema: “booking-status”: { “enum”: [ “PROCESSED”, “PENDING”, null ], “type”: “string” },

But also primitive type null should be added to the type list as It is declared here: https://json-schema.org/understanding-json-schema/reference/generic.html

So, instead of addition above, this should be added for the example: “booking-status”: { “enum”: [ “PROCESSED”, “PENDING”, null ], “type”: [ “string”, “null” ] },

Because It is not adding "null" primitive type to the type list to the Json schema; when I do this:

JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonSchema jsonSchema = factory.getJsonSchema( jsonNode ); jsonSchema.validate( jsonNode );

I get this false validation error: error: instance type (null) does not match any allowed primitive type (allowed: [“string”]) level: “error” schema: {“loadingURI”:“#”,“pointer”:“/properties/booking-status”} instance: {“pointer”:“/booking-status”} domain: “validation” keyword: “type” found: “null” expected: [“string”]

Can you please add the "null" primitive to the type list for Nullable enums?