I have a complex model class in Java
that has attributes of different class. I wanted to get the schema of the class in yml format for better readability. I was able get the structure of the class to a JSON file but I feel that yml is less cluttered and easy to ready.
Example From
public class Phone {
public String name;
public String number;
}
To
Phone:
fields:
name:
type: String
number:
type: String
The Jackson library offers the ability to generate a JSONSchema from a Java class. You should be able to serialize it into a YAML, although I haven't actually tested this part. Here how it might look like :
ObjectMapper m = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
m.acceptJsonFormatVisitor(m.constructType(Phone.class), visitor);
JsonSchema jsonSchema = visitor.finalSchema();
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.writeValue(yamlFile, jsonSchema);
You may need this configuration if you use enums
mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true);
More details at the github page of the Yaml module and the JSON schema module
If your use case is to just serialize your existing objects, without reading them first, you might try the approach from this answer using Jackson; it just writes to a file an example
object.
// Create an ObjectMapper mapper for YAML
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
// Write object as YAML file
mapper.writeValue(new File("/path/to/yaml/file"), example);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With