From a9659d5441e36d2a33ab51a7ddc852b851f51429 Mon Sep 17 00:00:00 2001 From: Corey Fritz Date: Thu, 15 Mar 2018 21:42:39 -0400 Subject: [PATCH] Avro fields with default values, or unions that include the null type, should not be included in required properties of JSON schema Combined fixes in the following PRs from the forked repository: https://github.com/fge/json-schema-avro/pull/2 https://github.com/fge/json-schema-avro/pull/3 --- .../avro/translators/RecordTranslator.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/fge/avro/translators/RecordTranslator.java b/src/main/java/com/github/fge/avro/translators/RecordTranslator.java index 28f470c..9e4a288 100644 --- a/src/main/java/com/github/fge/avro/translators/RecordTranslator.java +++ b/src/main/java/com/github/fge/avro/translators/RecordTranslator.java @@ -96,7 +96,9 @@ protected void doTranslate(final Schema avroSchema, fieldSchema = field.schema(); fieldType = fieldSchema.getType(); translator = AvroTranslators.getTranslator(fieldType); - required.add(fieldName); + if (isRequiredField(field)) { + required.add(fieldName); + } ptr = JsonPointer.of("properties", fieldName); propertyNode = FACTORY.objectNode(); properties.put(fieldName, propertyNode); @@ -107,6 +109,23 @@ protected void doTranslate(final Schema avroSchema, } } + private boolean isRequiredField(Schema.Field field) { + if (field.defaultValue() != null) { + return false; + } + + Schema fieldSchema = field.schema(); + if (fieldSchema.getType() == Schema.Type.UNION) { + for (Schema typeSchema : fieldSchema.getTypes()) { + if (typeSchema.getType() == Schema.Type.NULL) { + return false; + } + } + } + + return true; + } + private static void injectDefault(final ObjectNode propertyNode, final Schema.Field field) {