【发布时间】:2021-04-27 10:42:36
【问题描述】:
我想解析具有动态属性的 yaml 文件。所以,我有不同国家的 yaml 文件 - 荷兰.yml, usa.yml, uk.yml....等等
文件的内容将如下所示-
netherlands:
name: netherlands
type: country
location:
latitude: aaa
longitude: bbb
amsterdam:
name: amsterdam
type: city
latitude: xxx
longitude: yyy
rotterdam:
name: rotterdam
type: city
latitude: ddd
longitude: ggg
hague:
name: hague
type: city
latitude: kkk
longitude: lll
我想在我的代码中解析并以这种方式阅读它 -
@country(name="netherlands")
Country country;
country.getAmsterdam.getLatitude()
我正在使用 Springboot 和 Java 11。 如何使用注释来实现这一点?我相信我需要为每个国家/地区编写自定义注释。但主要问题是每个国家/地区的城市名称都是动态的,城市的数量也会因国家/地区而异。此外,可以稍后在 yaml 中添加城市。 我能够编写代码来解析 yaml 并将其映射到我的对象。但是到目前为止我看到的是,它需要映射到具有固定属性的类,这不是我的情况。这是我写的代码,但它不符合我的目的。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("netherlands.yml").getFile());
ObjectMapper om = new ObjectMapper(new YAMLFactory());
Country country = om.readValue(file, Country.class);
public class Country{
private String name ;
private String type;
private Location location;
// Here I need the dynamic attributes for my cities
}
我查看了很多文章,但找不到任何类似的例子。您能否建议一种方法来实现这一目标?非常感谢您的帮助。
【问题讨论】:
标签: java spring-boot annotations yaml