我在使用SnakeYaml将
java对象写入yml文件时遇到问题.我已经设置了一个spring boot项目,其中包含一个简单的application.yml,我将其转换为一组java对象.在实际应用程序中添加了一些对象,当应用程序完成时,我想写出新的application.yml.
输入application.yml看起来像这样:
sample:
name: toyota
cars:
- model: prius
colour: silver
- model: avensis
colour: red
映射此application.yml的java对象:
@Configuration
@ConfigurationProperties(prefix="sample")
public class Config {
private String name;
private final List cars = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getCars() {
return cars;
}
}
以及写出yaml的示例类:
@Component
public class Example {
@Autowired
private Config config;
@PostConstruct
private void init(){
Yaml yaml = new Yaml();
StringWriter writer = new StringWriter();
yaml.dump(config, writer);
System.out.println(writer.toString());
}
}
输出只是:name:toyota(省略了一些yaml设置也被写出来).但是我希望输出与输入完全相同:
sample:
name: toyota
cars:
- model: prius
colour: silver
- model: avensis
colour: red
有没有办法做到这一点?
编辑:
用户flyx正确地指出了以下documentation.
我调整后的代码:
Constructor constructor = new Constructor(Config.class);
TypeDescription configDescription = new TypeDescription(Config.class);
configDescription.putListPropertyType("cars", Car.class);
constructor.addTypeDescription(configDescription);
Yaml yaml = new Yaml(constructor);
StringWriter writer = new StringWriter();
yaml.dump(config, writer);
System.out.println(writer.toString());
给出以下输出:
$$beanFactory: !!org.springframework.beans.factory.support.DefaultListableBeanFactory
allowBeanDefinitionOverriding: true
allowEagerClassLoading: true
autowireCandidateResolver: !!org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver {}
beanClassLoader: !!sun.misc.Launcher$AppClassLoader {}
beanExpressionResolver: !!org.springframework.context.expression.StandardBeanExpressionResolver {}
cacheBeanMetadata: true
conversionService: null
dependencyComparator: !!org.springframework.core.annotation.AnnotationAwareOrderComparator {}
parentBeanFactory: null
serializationId: application
tempClassLoader: null
typeConverter: !!org.springframework.beans.SimpleTypeConverter {conversionService: null}
name: toyota
最佳答案 由于类型擦除,SnakeYAML无法在运行时获取List的元素类型.该文档包含您需要做的
example.
这样的事情应该有效:
@PostConstruct
private void init(){
Constructor c = new Constructor(Config.class);
TypeDescription configD = new TypeDescription(Config.class);
configD.putListPropertyType("cars", Car.class);
c.addTypeDescription(configD);
Yaml yaml = new Yaml(c);
StringWriter writer = new StringWriter();
yaml.dump(config, writer);
System.out.println(writer.toString());
}