You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SnakeYaml修改YAML无法保留原格式及字段,求解决方案

解决SnakeYAML修改YAML后格式异常及数据丢失问题

问题根源分析

你的代码存在三个核心问题:

  • 新建空Image对象覆盖原有数据,导致原有的repository和tag值丢失变为null
  • Dump时未使用配置好的DumperOptions,且错误传入用于解析加载的Constructor(Dump应搭配Representer)
  • 错误设置FlowStyle.FLOW,生成紧凑的花括号格式而非期望的块状缩进格式

修正后的代码

修改后的主类代码

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class SnakeYaml1 {

    public static void main(String[] args) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(new File("C:\\yaml\\student1.yaml"));
        
        // 加载原有YAML数据
        Yaml yaml = new Yaml(new Constructor(Values1.class));
        Values1 data = yaml.load(inputStream);
        
        // 直接修改原有Image对象的pullPolicy,不新建对象覆盖
        data.getImage().setPullPolicy("update");
        
        // 配置Dump选项,生成块状格式
        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        // 设置为BLOCK风格,生成换行缩进格式
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setIndicatorIndent(2);
        options.setIndentWithIndicator(true);
        
        // 使用Representer避免输出类全限定名标签
        Representer representer = new Representer(options);
        // 注册根类,防止输出!!oe.kubeapi.abc.Values1
        representer.addClassTag(Values1.class, null);
        
        Yaml yaml1 = new Yaml(representer, options);
        PrintWriter writer = new PrintWriter(new File("C:\\yaml\\student1.yaml"));
        yaml1.dump(data, writer);
        writer.close();
    }
}

实体类无需修改(保持原有的Values1和Image类即可)

关键修改点说明

  1. 保留原有数据:不再新建Image对象,直接调用data.getImage().setPullPolicy("update")修改已加载的对象,确保原有的repository和tag值被保留
  2. 正确配置Dump参数:
    • 用FlowStyle.BLOCK替代FlowStyle.FLOW,生成换行缩进的块状格式
    • 创建Representer并将根类标签设为null,避免输出类全限定名前缀
    • Dump时传入配置好的Representer和DumperOptions,而非错误的Constructor
  3. 关闭输出流:添加writer.close()确保数据正确写入文件

执行修改后的代码后,生成的YAML会符合期望:

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

内容的提问来源于stack exchange,提问作者user2315104

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:58:27