简体   繁体   中英

How to generate JsonSchema As Array from Java Class

I'm generating JsonSchema from Java class using fasterxml.jackson. The generated Jsonschema will be as below

    {
    "type": "object",
    "properties": {
      "id": {
        "type": "string"
      },
      "name": {
        "type": "string"
      }
     }
    }

My code to generate JsonSchema

public static String getJsonSchema(Class definitionClass) throws JsonProcessingException {
        ObjectMapper mapper =  new ObjectMapper().disable(
                MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
        JavaType javaType = mapper.getTypeFactory().constructType(definitionClass);
        JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
        JsonSchema schema = schemaGen.generateSchema(javaType);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
    }

I tried to use ArraySchema arraySchema = schema.asArraySchema(); but it generates invalid schema. My expected JsonSchema should be like below

  {
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "id": {
        "type": "string"
      },
      "name": {
        "type": "string"
      }
     }
    }
   }

TL;DR: Call getJsonSchema(MyClass[].class)


Works fine if we simply tell it to generate the schema of a Java array.

To demo, I created a MyClass class fitting the shown schema. I used public fields for simplicity of the demo, but we'd use private fields and public getter/setter methods in real life.

class MyClass {
    public String id;
    public String name;
}

Now, to show that we get the same result as in the question, we call it with MyClass.class :

System.out.println(getJsonSchema(MyClass.class));

Output

{
  "type" : "object",
  "id" : "urn:jsonschema:MyClass",
  "properties" : {
    "id" : {
      "type" : "string"
    },
    "name" : {
      "type" : "string"
    }
  }
}

Now, we want the schema to be an array of those, so we will instead call it using MyClass[].class .

System.out.println(getJsonSchema(MyClass[].class));

Output

{
  "type" : "array",
  "items" : {
    "type" : "object",
    "id" : "urn:jsonschema:MyClass",
    "properties" : {
      "id" : {
        "type" : "string"
      },
      "name" : {
        "type" : "string"
      }
    }
  }
}

The above was tested using jackson-module-jsonSchema-2.10.3.jar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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