简体   繁体   English

snakeyaml命名约定

[英]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. 从我所看到的情况来看,似乎对yaml命名约定的建议是遵循软件约定,因此在我的情况下为Java。

I've been given a yaml file with the following syntax 我收到了具有以下语法的yaml文件

PERSON:
  NAME: John Doe

I can't get snakeyaml to map correctly to my Person object unless I change from PERSON to person. 除非我从PERSON更改为person,否则我无法使snakeyaml正确映射到我的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. 从PERSON更改为person时,我可以读入所有大写字母的属性NAME,而没有任何问题。 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. 当我在yaml文件中将PERSON大写时,无论我的getter / setter语法是什么,我都无法得到snakeyaml进行加载。 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. 我已经尝试使用实例变量作为PERSON来尝试getPERSON / setPERSON,但是除非我在yaml文件中更改为person,否则它将无法正常工作。

You need to have fields name as present in yaml file because snakeyaml internally uses Reflection Api 您需要具有yaml文件中存在的字段名称,因为snakeyaml内部使用了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. 然后,您需要传递带有参数的Constructor类对象作为您的根类。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM