将 json 架构字段标记为必需的 xml 标记

Mark json schema field as required for required xml tags

我以如下方式从 XSD 生成 JSON 架构: https://dzone.com/articles/generating-json-schema-xsd

一切正常,但它不会将字段标记为 XSD 中标记为必需(或 minOccurs="1")的那些标记的必需字段。 杰克逊图书馆有可能吗? 或者其他工具?

我需要这样的东西:

{
"type": "object",
"required": true,
"properties": {
    "field": "value" ...

好的,这是一个答案。 您只需在 ObjectMapper 实例中注册新的 JaxbAnnotationModule 即可。 这是一个代码片段:

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;

    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = TypeFactory.defaultInstance();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(typeFactory);
    mapper.getDeserializationConfig().with(introspector);
    mapper.getSerializationConfig().with(introspector);

    //To force mapper to include JAXB annotated properties in Json schema
    objectMapper.registerModule(new JaxbAnnotationModule());
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
    objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(YOUR_JAXB_CLASS.class), visitor);

    JsonSchema inputSchema = visitor.finalSchema();
    String schemaString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(inputSchema);

    System.out.println(schemaString);