How to generate JSON schema from a JAXB annotated

2020-07-23 06:04发布

问题:

I have a entity class looks like this.

@XmlRootElement
public class ImageSuffix {

    @XmlAttribute
    private boolean canRead;

    @XmlAttribute
    private boolean canWrite;

    @XmlValue;
    private String value;
}

And I'm using following dependency for JSON generation.

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

When I tried with following code, (which referred from Generating JSON Schemas with 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;
    }
}

Server complains with following error message

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)

How can I fix this?

回答1:

Have you tried configuring your ObjectMapper to include jaxb introspector? We use spring mvc3 for implementing REST services and use the same model objects to serialize into xml/json.

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

EDIT: Here is the output I get from jackson:

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

Hope this helps!