如何生成从JAXB注解类JSON模式?(How to generate JSON schema fr

2019-08-21 03:16发布

我有一个实体类看起来是这样的。

@XmlRootElement
public class ImageSuffix {

    @XmlAttribute
    private boolean canRead;

    @XmlAttribute
    private boolean canWrite;

    @XmlValue;
    private String value;
}

而我使用JSON代以下的依赖。

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.1.4</version>
</dependency>

当我试图用下面的代码,(其从称为生成JSON架构和Jackson )

@Path("/imageSuffix.jsd")
public class ImageSuffixJsdResource {

    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public String read() throws JsonMappingException {

        final ObjectMapper objectMapper = new ObjectMapper();

        final JsonSchema jsonSchema =
            objectMapper.generateJsonSchema(ImageSuffix.class);

        final String jsonSchemaString = jsonSchema.toString();

        return jsonSchemaString;
    }
}

服务器与以下错误消息抱怨

java.lang.IllegalArgumentException: Class com.googlecode.jinahya.test.ImageSuffix would not be serialized as a JSON object and therefore has no schema
        at org.codehaus.jackson.map.ser.StdSerializerProvider.generateJsonSchema(StdSerializerProvider.java:299)
        at org.codehaus.jackson.map.ObjectMapper.generateJsonSchema(ObjectMapper.java:2527)
        at org.codehaus.jackson.map.ObjectMapper.generateJsonSchema(ObjectMapper.java:2513)

我怎样才能解决这个问题?

Answer 1:

您是否尝试过在配置ObjectMapper包括JAXB内省? 我们采用弹簧MVC3实现REST服务,并使用相同的模型对象序列化到XML / JSON。

AnnotationIntrospector introspector = 
    new Pair(new JaxbAnnotationIntrospector(), new JacksonAnnotationIntrospector());
objectMapper.setAnnotationIntrospector(introspector);
objectMapper.generateJsonSchema(ImageSuffix.class);

编辑 :这是我的输出从杰克逊得到:

{
  "type" : "object",
  "properties" : {
    "canRead" : {
      "type" : "boolean",
      "required" : true
    },
    "canWrite" : {
      "type" : "boolean",
      "required" : true
    },
    "value" : {
      "type" : "string"
    }
  }
}

希望这可以帮助!



文章来源: How to generate JSON schema from a JAXB annotated class?