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

Get SnakeYAML to serialize object hierarchy properly

我有以下基于 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

所以我问:

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

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