获取没有类标签的Yaml字符串

时间:2016-07-01 10:10:22

标签: java serialization tags yaml yamlbeans

是否有方法使用yamlbeans lib隐藏YamlWriter输出中的所有标记?

public <T> String toYaml(T object) {
    try (StringWriter stringWriter = new StringWriter()) {
        YamlWriter writer = new YamlWriter(stringWriter);
        writer.write(object);
        writer.getConfig().writeConfig.setWriteRootTags(false);//replaces only root tag
        writer.close(); //don't add this to finally, because it the text will not be flushed
        return removeTags(stringWriter.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

private String removeTags(String string) {
    //a tag is a sequence of characters starting with ! and ending with whitespace
    return removePattern(string, " ![^\\s]*");
}

谢谢。

1 个答案:

答案 0 :(得分:0)

将writers配置更改为从不编写类名,您就可以开始了:

writer.getConfig().writeConfig.setWriteClassname(YamlConfig.WriteClassName.NEVER);