【问题标题】:Mark json schema field as required for required xml tags将 json 模式字段标记为所需 xml 标记的必需项
【发布时间】:2018-02-21 19:55:34
【问题描述】:

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

一切正常,但它没有将 XSD 中标记为必需(或 minOccurs="1")的标记标记为必需的字段。 可以与杰克逊图书馆有关吗? 还是其他工具?

我需要这样的东西:

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

【问题讨论】:

  • 我知道的唯一选择是设置@JsonProperty(required = true)。但我的目标是在代码中生成JSON Schema,无需手动修改POJO

标签: java jackson jsonschema


【解决方案1】:

好的,这是一个答案。 您只需在 ObjectMapper 实例中注册新的 JaxbAnnotationModule。 这是一个代码sn-p:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 2018-03-22
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2021-07-03
    相关资源
    最近更新 更多