繁体   English   中英

从Java中的Pojo生成JSON模式-自定义日期类型

[英]Generate json schema from pojo in java - custom date type

我正在使用https://github.com/mbknor/mbknor-jackson-jsonSchema生成json模式,但是当我的对象包含LocalDate时,LocalDate将如下所示:

   "LocalDate" : {
      "type" : "object",
      "additionalProperties" : false,
      "properties" : {
        "year" : {
          "type" : "integer"
        },
        "month" : {
          "type" : "string",
          "enum" : [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ]
        },
        "era" : {
          "$ref" : "#/definitions/Era"
        },
        "dayOfYear" : {
          "type" : "integer"
        },
        "dayOfWeek" : {
          "type" : "string",
          "enum" : [ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" ]
        },
        "leapYear" : {
          "type" : "boolean"
        },
        "dayOfMonth" : {
          "type" : "integer"
        },
        "monthValue" : {
          "type" : "integer"
        },
        "chronology" : {
          "$ref" : "#/definitions/IsoChronology"
        }
      },
      "required" : [ "year", "dayOfYear", "leapYear", "dayOfMonth", "monthValue" ]
    },
    "Era" : {
      "type" : "object",
      "additionalProperties" : false,
      "properties" : {
        "value" : {
          "type" : "integer"
        }
      },
      "required" : [ "value" ]
    },
    "IsoChronology" : {
      "type" : "object",
      "additionalProperties" : false,
      "properties" : {
        "calendarType" : {
          "type" : "string"
        },
        "id" : {
          "type" : "string"
        }
      }
    }

有人可以帮我如何将LocalDate 类型更改为字符串并添加字段格式(即日期)吗?

自从我编写groovy插件以来,我的代码就在groovy中:

ObjectMapper mapper = new ObjectMapper()
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper)
JsonNode schema = jsonSchemaGenerator.generateJsonSchema(MyClass.class)

我希望LocalDate字段如下所示:

    "MyField": {
      "type": "string",
      "format": "date"
    }

感谢您的任何帮助。

您可以配置客户序列化程序并在该序列化程序中序列化LocalDate 例如(我从他们的github自述文件中复制了一个片段);

@JsonSerialize(using = MySpecialSerializer.class)
@JsonSchemaInject( json = "{\"//your schema here\"}" )
public class MyPojo {
  private LocalDate localDate;

  public LocalDate getLocalDate() {
    return localDate;
  }
  //and the rest the class
}
    public class MySpecialSerializer extends JsonSerializer<MyPojo>
    {

        @Override
        public void serialize(final MyPojo myPojo, 
                              final JsonGenerator gen, 
                              final SerializerProvider serializers) 
        throws IOException 
        {
           gen.writeObject(localDate.format(DateTimeFormatter.ISO_DATE));
           //and the other field serialization
        }

    }

如果需要,您还可以使用jackson的java-8 date模块。

您可以告诉模式生成器您要在模式中声明某种类型,就像它们是另一种类型一样。 因此,可以说您想将每个LocalDate声明为一个String。

为此,您需要创建一个JsonSchemaConfig对象,并将其传递给JsonSchemaGenerator构造函数。

classReMapping映射中,您可以将类型重新映射为其他类型。

Map<Class<?>, Class<?>> classTypeReMapping = new HashMap<>();
classTypeReMapping.put(LocalDate.class, String.class);

(可选)在typeToFormatMapping映射中,可以将类型映射到format注释。 您用于LocalDate的格式正是JSON模式规范中定义的格式date

Map<String, String> typeToFormatMapping = new HashMap<>();
typeToFormatMapping.put(LocalDate.class.getName(), "date");

构造一个完整的JsonSchemaConfig:

boolean autoGenerateTitleForProperties = false;
String defaultArrayFormat = null;
boolean useOneOfForOption = true;
boolean useOneOfForNullables = false;
boolean usePropertyOrdering = false;

boolean hidePolymorphismTypeProperty = false;
boolean disableWarnings = false;
boolean useMinLengthForNotNull = false;
boolean useTypeIdForDefinitionName = false;
boolean useMultipleEditorSelectViaProperty = false;
Set<Class<?>> uniqueItemClasses = Collections.emptySet();

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

Map<Class<?>, Class<?>> classTypeReMapping = new HashMap<>();
classTypeReMapping.put(LocalDate.class, String.class);
// #####****##### Add remapped types here 

Map<String, String> typeToFormatMapping = new HashMap<>();
typeToFormatMapping.put(LocalDate.class.getName(), "date");
// #####****##### (optional) Add format annotations for types here 

JsonSchemaConfig config = JsonSchemaConfig.create(
        autoGenerateTitleForProperties,
        Optional.ofNullable(defaultArrayFormat),
        useOneOfForOption,
        useOneOfForNullables,
        usePropertyOrdering,
        hidePolymorphismTypeProperty,
        disableWarnings,
        useMinLengthForNotNull,
        useTypeIdForDefinitionName,
        typeToFormatMapping,
        useMultipleEditorSelectViaProperty,
        uniqueItemClasses,
        classTypeReMapping,
        Collections.emptyMap()
)

构建一个JsonSchemaGenerator:

JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper, config);
Class<?> mainClassObject = ...;
JsonNode jsonSchema = jsonSchemaGenerator.generateJsonSchema(mainClassObject);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM