获取SnakeYAML以正确序列化对象层次结构

时间:2016-12-29 16:29:35

标签: configuration java-8 yaml snakeyaml

我有以下基于SnakeYAML的代码(v1.17):

public abstract class Beverage {
    protected int quantityOunces;

    // Getters, setters, ctors, etc.
}

public class AlcoholicBeverage extends Beverage {
    protected Double alcoholByVolume;

    // Getters, setters, ctors, etc.
}

public class SnakeTest {
    public static void main(String[] args) {
        new SnakeTest().serialize();
    }

    void serialize() {
        AlcoholicBeverage alcBev = new AlcoholicBeverage(20, 7.5);

        String alcYml = "/Users/myuser/tmp/alcohol.yml";

        FileWriter alcWriter = new FileWriter(alcYml);

        Yaml yaml = new Yaml();

        yaml.dump(alcBev, alcWriter);
    }
}

生成以下/Users/myuser/tmp/alcohol.yml文件:

!!me.myapp.model.AlcoholicBeverage {}

我原本希望文件的内容类似于:

quantityOunces: 20
alcoholByVolume: 7.5

所以我问:

  • 如何让yaml.dump(...)将对象属性正确序列化到文件中?和
  • 那个!!me.myapp.model.AlcoholicBeverage {}元数据很烦人......无论如何要配置Yaml忽略/忽略它?

1 个答案:

答案 0 :(得分:1)

您可以通过修改代码获得所需的输出,如下所示:

<强> SnakeTest.java

import java.io.FileWriter;
import java.io.IOException;

import org.yaml.snakeyaml.Yaml;

abstract class Beverage {
    protected int quantityOunces;

    public int getQuantityOunces() {
        return quantityOunces;
    }

    public void setQuantityOunces(int quantityOunces) {
        this.quantityOunces = quantityOunces;
    }

}

class AlcoholicBeverage extends Beverage {
    protected Double alcoholByVolume;

    public AlcoholicBeverage(int quatityOnces, double alcoholByVolume) {
        this.quantityOunces = quatityOnces;
        this.alcoholByVolume = alcoholByVolume;
    }

    public Double getAlcoholByVolume() {
        return alcoholByVolume;
    }

    public void setAlcoholByVolume(Double alcoholByVolume) {
        this.alcoholByVolume = alcoholByVolume;
    }

}

public class SnakeTest {
    public static void main(String[] args) throws IOException {
        new SnakeTest().serialize();
    }

    void serialize() throws IOException {
        AlcoholicBeverage alcBev = new AlcoholicBeverage(20, 7.5);

        String alcYml = "/Users/myuser/tmp/alcohol.yml";

        Yaml yaml = new Yaml();
        try (FileWriter alcWriter = new FileWriter(alcYml)) {
            alcWriter.write(yaml.dumpAsMap(alcBev));
        }

    }
}

代码已包含在具有以下内容的maven项目中 的的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SnakeYAML</groupId>
  <artifactId>SnakeYAML</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.17</version>
    </dependency>
  </dependencies>
</project>

输出是:

alcoholByVolume: 7.5
quantityOunces: 20