Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Java class structure to yml file

Tags:

java

json

yaml

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
like image 674
Nandish A Avatar asked Sep 27 '22 08:09

Nandish A


2 Answers

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

like image 163
Manos Nikolaidis Avatar answered Sep 30 '22 09:09

Manos Nikolaidis


From RAM to File

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);
like image 41
manuelvigarcia Avatar answered Sep 30 '22 09:09

manuelvigarcia