英文:
Read and map property file without Spring
问题
我有一个名为 property.yaml
的文件:
table:
map:
0:
- 1
- 2
- 3
1:
- 1
- 2
- 3
- 4
2:
- 1
- 2
- 3
3:
- 1
- 2
- 3
我想将其映射为 Map<Integer, List<Integer>> map
。使用 @ConfigurationProperties("table")
可以很容易地完成此任务,但我必须在没有 Spring
的情况下完成。有任何想法吗?
英文:
I have a property.yaml
file:
table:
map:
0:
- 1
- 2
- 3
1:
- 1
- 2
- 3
- 4
2:
- 1
- 2
- 3
3:
- 1
- 2
- 3
I want to map it to Map<Integer, List<Integer>> map
. It's easy task with @ConfigurationProperties("table")
. But I have to do it without Spring
. Any idea?
答案1
得分: 3
Spring使用snakeyaml,因此它已经在您的类路径上,您可以直接使用它。如果您需要更多信息,可以访问项目页面这里。
在您的情况下,您可以像这样操作:
Yaml yaml = new Yaml(new Constructor(Yourclass));
Yourclass yc = (Yourclass) yaml.load(yourfile);
Map<Integer, List<Integer>> map = yc.map;
英文:
Spring uses snakeyaml so it is already on your classpath, you can use it out of the box. The project page is here if you need more info.
In your case you can do something like this:
Yaml yaml = new Yaml(new Constructor(Yourclass));
Yourclass yc = (Yourclass) yaml.load(yourfile);
Map<Integer, List<Integer>> map = yc.map;
答案2
得分: 0
感谢 @Adam Arold 的帮助。解决方案:
FileProperties.class
@Getter
@Setter
public class FileProperties {
private Map<String, List<String>> table;
}
MyClass
public class MyClass {
public FileProperties readYaml(String filename) {
Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(filename);
return yaml.load(inputStream);
}
}
yaml
!!com.test.test.FileProperties
table:
key1:
- value1
- value12
- value13
key2:
- value11
- value12
- value15
key3:
- value11
- value12
- value15
请注意 !!com.test.test.FileProperties
包含了加载时要使用的类的信息。
英文:
Thanks @Adam Arold for help. Solution:
FileProperties.class
@Getter
@Setter
public class FileProperties {
private Map<String, List<String>> table;
}
MyClass
public class MyClass {
public FileProperties readYaml(String filename) {
Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(filename);
return yaml.load(inputStream);
}
yaml
!!com.test.test.FileProperties
table:
key1:
- value1
- value12
- value13
key2:
- value11
- value12
- value15
key3:
- value11
- value12
- value15
Note the !!com.test.test.FileProperties
holds the info about the class to be used when loading it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论