Generate Schema for getters without corresponding fields #380
-
|
Hi is there anyway that I can generate the schema for getters that have no corresponding field easily? Tried a couple of the Options but having trouble to get this to work. So for example if I have the class: public class TestGetter {
private String fieldThatWillGenerate;
public TestGetter() {
}
public String getFieldThatWillNotGenerate() {
return "";
}
public String getFieldThatWillGenerate() {
return this.fieldThatWillGenerate;
}
}and the code @Test
public void testGetterGeneration()
throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
final JacksonModule module = new JacksonModule();
final SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(mapper,
SchemaVersion.DRAFT_2020_12,OptionPreset.PLAIN_JSON)
.with(module);
final SchemaGeneratorConfig config = configBuilder.build();
final SchemaGenerator generator = new SchemaGenerator(config);
final String actualJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(generator.generateSchema(TestGetter.class));
System.out.println(actualJson);
}then the output would be {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"fieldThatWillGenerate" : {
"type" : "string"
}
}
}but I would like it to be {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"fieldThatWillGenerate" : {
"type" : "string"
},
"fieldThatWillNotGenerate" : {
"type" : "string"
}
}
}so that it includes the suffix of the getter as the fieldname or the name using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
HI @nickkhine, I suggest you have a look at the documentation: Since you're using the Regarding the naming, However, this may include methods you don't want to be reflected in your JSON Schema (such as configBuilder.forMethods()
.withIgnoreCheck(method -> !method.getDeclaredName().startsWith("get")); |
Beta Was this translation helpful? Give feedback.
HI @nickkhine,
I suggest you have a look at the documentation:
https://victools.github.io/jsonschema-generator/#generator-options
Since you're using the
OptionPreset.PLAIN_JSON, you're missing theOption.NONSTATIC_NONVOID_NONGETTER_METHODSby default, which you should add explicitly in order for thegetFieldThatWillNotGenerate()method to be considered.Regarding the naming,
Option.FIELDS_DERIVED_FROM_ARGUMENTFREE_METHODSwould take care of your example.The
JacksonModulewould use the@JsonPropertyannotation's value instead if it is present.However, this may include methods you don't want to be reflected in your JSON Schema (such as
toString()).Therefore you could either use the
Jacks…