gpt4 book ai didi

java - SnakeYAML:如何设置用于加载的 bean 属性类型

转载 作者:行者123 更新时间:2023-11-30 02:57:43 36 4
gpt4 key购买 nike

使用 SnakeYAML 的 TypeDescription,我可以使用以下方法添加有关列表和 map 的类型信息:

TypeDescription td = new TypeDescription(MyBean.class, "!mybean");
td.putMapPropertyType("mymap", String.class, MyOtherBean.class);
td.putListPropertyType("mylist", MyOtherBean.class);

这样,我就可以用 MyOtherBean 的实例填充集合,而不必依赖任何其他标签:

---
!mybean
mymap:
foobar: # will map to an instance of MyOtherBean
otherbeanprop1: foo
otherbeanprop2: bar
mylist: # will contain instances of MyOtherBean
- otherbeanprop1: foo
otherbeanprop2: bar

有没有简单的方法可以做这样的事情:

td.putPropertyType("myotherbean", MyOtherBean.class);

以便 MyBean 中的属性 myotherbean 将由 MyOtherBean 的单个实例填充?我试图避免的事情:

  • 在 yaml 文件中添加其他标签(如 !myotherbean)
  • 从 Map 加载其他 beans 属性并自己构建 bean

我已经尝试过这个,我想我需要创建一个像这样的自定义构造函数(改编自 SnakeYAML 文档):

class SelectiveConstructor extends Constructor {
public SelectiveConstructor() {
// define a custom way to create a mapping node
yamlClassConstructors.put(NodeId.mapping, new ConstructMapping() {
@Override
protected Object constructJavaBean2ndStep(MappingNode node, Object object) {
Class type = node.getType();
if (type.equals(MyBean.class)) {
// something
if (propertyname.equals("myotherbean")) {
// something
}
} else {
// redirect creation to Constructor
return super.constructJavaBean2ndStep(node, object);
}

}
}
}

问题是我不太明白那里到底发生了什么。如果有更简单的方法,请告诉我。如果没有,如果您分享您的经验,我将不胜感激。

最佳答案

有一种优雅的方法可以做到这一点。
如果你不想对YAML内容做一些特殊的处理,你可以使用snakeYaml的以下两个方法来转储和加载yaml内容:

public String dumpAsMap(Object data)              // dump method
public <T> T loadAs(Reader io, Class<T> type) // load method

在您的场景中,

转储:

MyBean bean = new MyBean();
// init bean...
String yamlContent = yaml.dumpAsMap(bean);

负载:

FileReader reader = new FileReader(filename);
MyBean bean = yaml.loadAs(reader, MyBean.class);

当然,您应该实现类的 getter 和 setter。详情可以查看example在这里。

关于java - SnakeYAML:如何设置用于加载的 bean 属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36789242/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com