首页 > 解决方案 > SnakeYaml 未序列化私有或受保护字段

问题描述

我正在尝试使用 SnakeYaml 转储/序列化 Java POJO,并且未序列化私有和受保护字段。

public class Dice {
    private Integer a;
    protected Integer b;
    public Integer c;

    public Dice(Integer a, Integer b, Integer c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Integer getA() {
        return a;
    }

    public Integer getB() {
        return b;
    }

    public Integer getC() {
        return c;
    }

    public static void main(String[] args) {
            Dice dice = new Dice(1,2,3);
            Yaml yaml = new Yaml();
            String output = yaml.dump(dice);
            System.out.println(output);
    }
}

产生以下内容:

!!com.ibm.watson.pml.gpm.plan.Dice {c: 3}

我已经看到很多例子表明私有和受保护的字段被正确序列化。我尝试了 1.17 和 1.23,结果相同。

标签: javasnakeyaml

解决方案


Yaml.setBeanAccess(BeanAccess.FIELD);


推荐阅读