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

如何配置SnakeYAML移除RAML中!include语句的单引号?

问题描述

使用SnakeYAML生成RAML文件时,sortable字段的type值被自动添加了外层单引号,不符合预期格式:

#%RAML 1.0 DataType
type: object
properties:
  apiName:
    type: string
  label:
    type: string
  sortable:
    type: '!include boolean-types.raml'

需要移除!include boolean-types.raml外层的单引号,当前使用的SnakeYAML配置代码如下:

DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
yaml.dump(map, writer);
解决方案

SnakeYAML默认会给包含!这类特殊字符的字符串添加引号,要解决这个问题,需要自定义Representer来强制指定!include开头的内容以无引号的纯文本格式输出:

  1. 实现自定义Representer:
class RamlRepresenter extends Representer {
    public RamlRepresenter(DumperOptions options) {
        super(options);
    }

    @Override
    protected Node representScalar(Tag tag, String value, Style style) {
        if (value.startsWith("!include")) {
            // 强制使用PLAIN风格输出,避免添加引号
            return super.representScalar(tag, value, DumperOptions.Style.PLAIN);
        }
        return super.representScalar(tag, value, style);
    }
}
  1. 修改YAML实例的创建逻辑,传入自定义的Representer:
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
// 使用自定义Representer替代默认实现
Yaml yaml = new Yaml(new RamlRepresenter(options));
yaml.dump(map, writer);

调整后生成的RAML代码中,sortable字段的type值会变为:

sortable:
  type: !include boolean-types.raml

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:16:14