Uninitialize a nested class using yamlbeans

I am using yamlbeans to deserialize yaml files in Java objects. This works great as long as I have only one class. The problem is that when I want to nest a field, I am forced to specify a nested class in the yaml description.

An example of one class:

Java:

public class MessageField { public String name; public String type; public int length; public String comment; } 

YAML:

 name: field1 type: int length: 4 comment: first field --- name: field2 type: string length: 16 comment: second field --- 

Multiple classes (required! Com.mylib.VariableField in yaml file)

Java:

 public class MessageField { public String name; public String type; public int length; public String comment; public List<VariableField> variableFields; } public class VariableField extends MessageField{ public int id; } 

YAML:

 name: field3 type: short length: 2 comment: variableFields: - !com.mylib.VariableField id: 1 name: nestedField 1 type: string length: -1 comment: --- 

The yaml documentation page describes how to deserialize the class by specifying the type when reading the class, which is what I do for the top-level class:

 YamlReader reader = new YamlReader(new FileReader("sample.yml")); MessageField mf = reader.read(MessageField.class); 

This parses my fields correctly for the top-level class, but does not allow me to avoid the identifier! com.mylib.VariableField for my nested class. I am trying to figure out if there is a way to change the Java code so that yaml files do not require to know the class name.

+4
source share
1 answer

I believe what you are looking for

 reader.getConfig().setPropertyElementType(MessageField.class, "variableFields", VariableField.class); 

which sets the default item type for collection-based fields. Similarly, the setPropertyDefaultType method can be used to specify the default type for the field itself.

When using the default field types / types defined for YamlReader, you no longer need to include the class names in the yaml file (although any type names you include will override these default values). Also, if type types are set to YamlWriter by default, extra class names will not be written to the yaml file.

+7
source

Source: https://habr.com/ru/post/1398683/


All Articles