Search code examples
javasnakeyaml

snakeyaml naming convention


From what I've seen it looks like the recommendation on yaml naming conventions is to follow the software convention, so in my case Java.

I've been given a yaml file with the following syntax

PERSON:
  NAME: John Doe

I can't get snakeyaml to map correctly to my Person object unless I change from PERSON to person. I've also tried with other variable names but only camel case or lower case object names seem to work. I can read in the all caps attribute NAME without any issues as a String when I change from PERSON to person. Can someone explain why this is the case?

public class Configuration {

  private Person person;

  public Configuration() {
    person = new Person();
  }

  public Person getPerson() {
    return person;
  }

  public void setPerson(Person person) {
    this.person = person;
  }

}

When I capitalize PERSON in the yaml file no matter the syntax of my getter/setter I can't get snakeyaml to load it. I've tried getPERSON/setPERSON with my instance variable as PERSON, but it doesn't work unless I change to person in the yaml file.


Solution

  • You need to have fields name as present in yaml file because snakeyaml internally uses Reflection Api

    So your class looks like this-

     class Configuration {
    
        public Person PERSON;
    
        public Person getPERSON() {
            return PERSON;
        }
    
        public void setPERSON(Person PERSON) {
            this.PERSON = PERSON;
        }
    }
    
    class Person {
    
        public String NAME;
    
        public String getNAME() {
            return NAME;
        }
    
        public void setNAME(String NAME) {
            this.NAME = NAME;
        }
    }
    

    Note that fields need to be public as stated here

    Then you need to pass the Constructor class object with the parameter as your root class.

    Yaml yaml = new Yaml(new Constructor(Configuration.class));
    

    Full code..

    class Test {
    
        public static void main(String[] args) throws FileNotFoundException {
            String filePath = "path/to/configuartion/file/configuration.yaml";
            InputStream input = new FileInputStream(new File(filePath));
            Yaml yaml = new Yaml(new Constructor(Configuration.class));
            Configuration configuration = yaml.load(input);
        }
    }