java 无法使用SnakeYaml保持原始方式格式化YAML

jhkqcmku  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(241)

拥有以下YAML

image:
  repository: "test.com/test"
  pullPolicy: IfNotPresent
  tag: "abc"

修改YAKL文件的JAVA代码

public class SnakeYaml1 {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        
        InputStream inputStream = new FileInputStream(new File("C:\\yaml\\student1.yaml"));
        
        Yaml yaml = new Yaml(new Constructor(Values1.class));
    
        Values1 data = yaml.load(inputStream);
        Image image = new Image();
        image.setPullPolicy("update");
        data.setImage(image);
        
        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
        options.setIndicatorIndent(2);
        options.setIndentWithIndicator(true);
        
        PrintWriter writer = new PrintWriter(new File("C:\\yaml\\student1.yaml"));
        Yaml yaml1 = new Yaml(new Constructor(Values1.class));
        yaml1.dump(data, writer);

    }
}

public class Values1 {
    
    private Image image;

    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }
}

public class Image {
    
    private String repository;
    private String pullPolicy;
    private String tag;
    
    public Image()
    {   
    }
    
    public Image (String repository, String pullPolicy, String tags)
    {
        super();
        this.repository = repository;
        this.pullPolicy = pullPolicy;
        this.tag = tags;
        
    }
    
    public String getRepository() {
        return repository;
    }
    public void setRepository(String repository) {
        this.repository = repository;
    }
    public String getPullPolicy() {
        return pullPolicy;
    }
    public void setPullPolicy(String pullPolicy) {
        this.pullPolicy = pullPolicy;
    }
    public String getTag() {
        return tag;
    }
    public void setTag(String tag) {
        this.tag = tag;
    }
    

}

在执行java代码后,YAML格式发生了变化

执行JAVA代码后的YAML格式

!!oe.kubeapi.abc.Values1
image: {pullPolicy: update, repository: null, tag: null}

java代码执行后的YAML格式

image:
      repository: "test.com/test"
      pullPolicy: update
      tag: "abc"

不明白为什么YAML格式在执行Java代码后会发生变化。这是SnakeYaml中的bug吗??
我试着把属性图像列表格式以及,List<Image> image仍然没有工作
请给我建议。该怎么做有什么需要帮忙的吗?

3wabscal

3wabscal1#

好吧,你提到它是SnakeYaml库,所以我想知道你有没有看过它的文档?
你的代码会像它应该的那样工作。
尝试:

DumperOptions options = new DumperOptions();
 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
 Yaml yaml  = new Yaml(options);

相关问题