Search code examples
javayamlsnakeyaml

YAML custom object


I have simple YAML document:

object:
  a: 1
  b: 2
  c: 3

Could I read this properties to custom object, which contains a constructor only with 1 argument. For example

public class CustomObject {
        private String value;

        public CustomObject(String value) {
            ....
        }

        getValue ...
        setValue ...
    }

where value is result of properties concatenation a,b,c with mask (as result 1:2/3)?


Solution

  • This is possible with custom constructors and representers:

    class CustomObjectConstructor extends Constructor {
        public CustomObjectConstructor() {
            this.yamlConstructors.put(new Tag("!customObject"), new ConstructCustomObject());
        }
    
        private class ConstructCustomObject extends AbstractConstruct {
            public Object construct(Node node) {
                final Map<Object, Object> values = constructMapping(node);
                final String a = (String) values.get("a");
                final String b = (String) values.get("b");
                final String c = (String) values.get("c");
                return new CustomObject(a + ":" + b + "/" + c);
            }
        }
    }
    

    You can use it like this:

    Yaml yaml = new Yaml(new CustomObjectConstructor());
    CustomObject myObject =
        (CustomObject) yaml.load("!customObject\na: 1\nb: 2\nc: 3");
    

    Of course, this needs refinement for handling error cases, but it shows the general idea. To dump the object as a mapping, you can define a representer similarly to the code here. See the documentation for more information.