如何配置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开头的内容以无引号的纯文本格式输出:
- 实现自定义
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); } }
- 修改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
相关产品推荐
相关产品推荐

