将Groovy映射转换为Yaml格式的字符串 [英] Convert Groovy Map to String in Yaml format

查看:475
本文介绍了将Groovy映射转换为Yaml格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用snakeYaml将YAML格式的字符串 转换为 Groovy 地图.

@Grab(group='org.yaml', module='snakeyaml', version='1.17')
import org.yaml.snakeyaml.Yaml

Yaml yaml = new Yaml()

Map config = yaml.load(new File('config.yaml').text)

我现在想得出相反的结论:给定Groovy Map ,我想将其转换为YAML格式的 String ,而无需在文件中写入字符串.

我找到了groovy.yaml.YamlBuilder.但是,该环境的常规编译器很旧,找不到此类.

理想情况下,相同的库(snakeYaml)可以处理相反的情况.但是没有办法使它起作用.

解决方案

是的yaml.dump()是答案


Map config = [kind: 'Pod', metadata:[name: app]]

Yaml yaml = new Yaml()

assert yaml.dump(config) == '''kind: Pod
metadata:
  name: app
'''

I am using snakeYaml to convert a String in YAML format to Groovy Map.

@Grab(group='org.yaml', module='snakeyaml', version='1.17')
import org.yaml.snakeyaml.Yaml

Yaml yaml = new Yaml()

Map config = yaml.load(new File('config.yaml').text)

I want to reach now the opposite : Given a Groovy Map, i want to convert it to String in YAML format WITHOUT WRITING THE STRING in a FILE.

I found groovy.yaml.YamlBuilder. However, the groovy compiler of the environment is old and this class is not found.

Ideally, the same lib (snakeYaml) can handle the opposite case. But no way to get it work.

解决方案

yes yaml.dump() is the answer


Map config = [kind: 'Pod', metadata:[name: app]]

Yaml yaml = new Yaml()

assert yaml.dump(config) == '''kind: Pod
metadata:
  name: app
'''

这篇关于将Groovy映射转换为Yaml格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆