Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JsonSchemaGenerator - How to get Schema as String

I'm sure I'm just being dense here.

I want to take an object schema, and turn it into a string representation.

Like so, but this returns null:

JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER);
JsonSchema jsonSchema = generator.generateSchema(Get.class);
System.out.println("jsonSchema: " + jsonSchema.asObjectSchema().asStringSchema());

This is using com.fasterxml.jackson.module.jsonSchema.JsonSchema, found at https://github.com/FasterXML/jackson-module-jsonSchema/wiki

like image 395
mtyson Avatar asked Jan 09 '23 10:01

mtyson


2 Answers

you can achieve that by doing:

ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(mapper.constructType(YOURCLASS.class), visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
like image 178
Thiago Burgos Avatar answered Jan 17 '23 02:01

Thiago Burgos


Easily done:

m.writeValueAsString(jsonSchema);

Essentially, using Jackson to marshal the schema object into JSON.

like image 43
mtyson Avatar answered Jan 17 '23 03:01

mtyson