如何使用Jackson在JSON Schema中显示属性默认值
Hey there! I’ve run into exactly this issue before—turns out the default parameter in @JsonProperty isn’t meant for JSON Schema generation at all. That parameter is used internally by Jackson during deserialization to set a fallback value if the field is missing from the input JSON, but the JsonSchemaGenerator doesn’t actually read it.
Here’s how to fix it:
Step 1: Use the @JsonSchema annotation
You’ll want to use the @JsonSchema annotation (from the Jackson JSON Schema module) to explicitly define default values that will show up in your generated schema. This annotation is purpose-built for schema metadata, so the generator will pick it up correctly.
First, make sure you have the Jackson JSON Schema module in your dependencies. If you’re using Maven, add this to your pom.xml:
<dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jsonSchema</artifactId> <version>your-jackson-version</version> </dependency>
Step 2: Update your entity class
Modify your RootTemplate class to replace (or supplement) the @JsonProperty default with @JsonSchema(defaultValue = ...). For example:
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.module.jsonSchema.annotations.JsonSchema; public class RootTemplate { @JsonProperty("username") @JsonSchema(defaultValue = "guest") private String username; @JsonProperty("isActive") @JsonSchema(defaultValue = "true") private boolean isActive; @JsonProperty("maxRetries") @JsonSchema(defaultValue = "3") private int maxRetries; // Getters and setters here }
Note: For non-string types, you still pass the value as a string in the annotation—Jackson’s schema generator will automatically convert it to the correct JSON type in the output schema.
Step 3: Regenerate your schema
Your existing schema generation code doesn’t need any changes! When you run it now, the output JSON Schema will include the default field for each annotated property.
For the example above, the generated schema would look something like this (abbreviated):
{ "type" : "object", "properties" : { "username" : { "type" : "string", "default" : "guest" }, "isActive" : { "type" : "boolean", "default" : true }, "maxRetries" : { "type" : "integer", "default" : 3 } } }
That’s it—this should get your default values showing up in the generated schema as expected.
内容的提问来源于stack exchange,提问作者Tarun

