使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忽略/省略它?

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

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

最新更新