如题所示,一般yaml结构中,字符串直接显示没有单引号的字符串,如果字符串由数字组成,为了区别真正的数字,这个字符串会使用单引号包围起来。
数据结构如下:
Map<String,Object> map = new LinkedHashMap<>(){
{
put("name","buejee");
put("age",18);
put("number","200");
}
};
默认,生成的yaml如下所示:
name: buejee
age: 18
number: '200'
这个结果是我们使用snakeyaml默认生成的,我们也许会想着设置yaml显示属性,比如设置:
options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
最终,我们的yaml结果生成是这样的:
"name": "buejee"
"age": !!int "18"
"number": "200"
这回,不管是不是字符串,统统都加了双引号。
我们其实想要的结果是这样的:
name: buejee
age: 18
number: "200"
其实是有解决办法的,我们需要自定义一个String类型,比如QuotedString,然后我们自定义一个RepresenterQuotedString实现Represent接口。
完整实现如下所示:
pom.xml依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.30</version>
</dependency>
自定义QuotedString.java
package com.yaml;
public class QuotedString {
public String value;
public QuotedString(String value) {
this.value = value;
}
}
自定义生成器MyRepresenter.java
package com.yaml;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
public class MyRepresenter extends Representer {
public MyRepresenter(){
this.representers.put(QuotedString.class,new RepresenterQuotedString());
}
public class RepresenterQuotedString implements Represent {
@Override
public Node representData(Object o) {
if (o instanceof QuotedString) {
QuotedString str = (QuotedString) o;
return representScalar(Tag.STR, str.value, DumperOptions.ScalarStyle.DOUBLE_QUOTED);
}
return null;
}
}
}
测试类YamlTest.java
package com.yaml;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
public class YamlTest {
public static void main(String[] args) throws IOException {
Map<String, Object> map = new LinkedHashMap<>() {
{
put("name", "buejee");
put("age", 18);
put("number", new QuotedString("200"));
}
};
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setIndentWithIndicator(true);
options.setIndicatorIndent(2);
Yaml yaml = new Yaml(new MyRepresenter(), options);
StringWriter writer = new StringWriter();
yaml.dump(map, writer);
System.out.println(writer);
}
}
运行结果:
这里自定义生成器与其他自定义生成器不矛盾,如果我们定义了空值生成器,可以替换snakeyaml默认的空值生成器,只需要在自定义生成器中这样设置即可:
public MyRepresenter(){
this.nullRepresenter = new NullRepresenter();
this.representers.put(QuotedString.class,new RepresenterQuotedString());
}
这里可以看出,空值生成器与其他自定义生成器设置不一样。
当然,我们也要自定义NullRepresenter。
最后,我们在实例化Yaml()的时候,传入MyRepresenter,如下所示:
Yaml yaml = new Yaml(new MyRepresenter(), options);