How to programmatically generate JsonSchema representing binary content in Java #271
-
We have a Rest API which allows clients to GET back some binary content (e.g. Image) We are using JsonSchema to help describe the API in question so I want to built out a JsonSchema representing that content. Looking through json-schema.org's recommendation called out HERE The relevant JsonSchema can be represented as the following String Schema:
So was wondering if I may be missing something obvious and if anyone else happened to have any pointers on what can be done in this situation in order to generate the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @lzemskov, Some context might be helpful here. Is your API just returning binary content directly?
public class BinarySchemaExample {
public static void main(String[] args) throws JsonProcessingException {
SchemaGeneratorConfigBuilder config = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
config.forTypesInGeneral().withCustomDefinitionProvider(new CustomBinaryDefinitionProvider());
SchemaGenerator generator = new SchemaGenerator(config.build());
JsonNode jsonSchema = generator.generateSchema(Foo.class);
System.out.println(jsonSchema.toPrettyString());
}
static class Foo {
String name;
Bar content;
}
static class Bar {
byte[] binaryData;
}
static class CustomBinaryDefinitionProvider implements CustomDefinitionProviderV2 {
@Override
public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
if (!javaType.isInstanceOf(Bar.class)) {
return null;
}
ObjectNode subschema = context.getGeneratorConfig().createObjectNode()
.put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_STRING))
.put("contentEncoding", "base64")
.put("contentMediaType", "image/png");
return new CustomDefinition(subschema, CustomDefinition.DefinitionType.STANDARD, CustomDefinition.AttributeInclusion.NO);
}
}
} The generated schema looks like this then: {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"content" : {
"type" : "string",
"contentEncoding" : "base64",
"contentMediaType" : "image/png"
},
"name" : {
"type" : "string"
}
}
} You might want to be a bit smarter about where the |
Beta Was this translation helpful? Give feedback.
Hi @lzemskov,
Some context might be helpful here. Is your API just returning binary content directly?