简体   繁体   中英

How can i generate JSON schema with a required filed or default values?

im using jackson to handle JSON objects, and i want a way to generate a schema from a class that i can enforce on the objects. i found out that i can use this :

JsonSchemaGenerator generator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = generator.generateSchema(DBUser.class);
mapper.writeValueAsString(jsonSchema);

using this com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator.
generated from this class:

public class DBUser {

    private String database="stu";
    private int role;
    private String username;
    private String password;
    //setters and getters defined
    }

which gives me this :

{
  "type" : "object",
  "id" : "urn:jsonschema:DBUser",
  "properties" : {
    "database" : {
      "type" : "string"
    },
    "role" : {
      "type" : "integer"
    },
    "username" : {
      "type" : "string"
    },
    "password" : {
      "type" : "string"
    }
  }
}

what i need is a required field like this :

"required": ["database","role","username"]

but it has no required field, or initial values, which i need. so how can i get that ?

You can annotate your pojo DBUser class fields with the JsonProperty#required set to true to generate a jsonschema with required fields:

public class DBUser {

    @JsonProperty(required = true)
    private String database = "stu";
    @JsonProperty(required = true)
    private int role;
    @JsonProperty(required = true)
    private String username;
    private String password;
}

//generate the new jsonschema with the required fields
JsonSchemaGenerator generator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = generator.generateSchema(DBUser.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter()
                         .writeValueAsString(jsonSchema));


//json generated
{
  "type" : "object",
  "id" : "urn:jsonschema:DBUser",
  "properties" : {
    "database" : {
      "type" : "string",
      "required" : true
    },
    "role" : {
      "type" : "integer",
      "required" : true
    },
    "username" : {
      "type" : "string",
      "required" : true
    },
    "password" : {
      "type" : "string"
    }
  }
}

Note that according to the documentation the jsonschema module supports the creation of a JSON Schema (v3) and not upper JSON Schema versions, so keywords introduced in later versions are not supported.

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