问题描述
我有一个类 Recipe
代表这个 YAML 块:
I have a class Recipe
that represents this YAML block:
id: Ex1
uses:
- Database: ["D1", "D2"]
- MetaFeature: ["M1", "M2"]
- Algorithm: ["A1", "A2"]
- Config: ["C1", "C4"]
public class Recipe {
private String id;
private HashMap<String, HashSet<String>> uses;
}
有没有办法将这个 YAML 解析为 Recipe 类,而无需创建其他类或做一些技巧?
Is there a way to parse this YAML to Recipe class without creating other classes or doing some tricks?
推荐答案
首先,您必须将 SnakeYML 作为依赖项包含在 maven pom.xml 中.我在下面提供了snakeyml的maven依赖.
Firs of all, you have to include SnakeYML as dependency in maven pom.xml. I provide below the maven dependency for snakeyml.
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.21</version>
</dependency>
如果你不使用Maven,你可以从下面的链接下载jar文件.http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar
If you are not using Maven, you can download the jar file from the following link.http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar
我修改了您的 yml 文件位以使其正常工作.在下面找到 yml 文件的结构.
I modified your yml file bit to make it work. Find below the structure of yml file.
id: Ex1
uses:
Database: ["D1", "D2"]
MetaFeature: ["M1", "M2"]
Algorithm: ["A1", "A2"]
Config: ["C1", "C4"]
让我为您提供有效的代码.
Let me provide you the code which is working.
import java.util.HashMap;
import java.util.HashSet;
public class Recipe {
private String id;
private HashMap<String, HashSet<String>> uses;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public HashMap<String, HashSet<String>> getUses() {
return uses;
}
public void setUses(HashMap<String, HashSet<String>> uses) {
this.uses = uses;
}
@Override
public String toString() {
return "Recipe{" + "id='" + id + '\'' + ", uses=" + uses + '}';
}
}
根据您的食谱类测试代码.
Test code as per your Recipe class.
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
public class TestYml {
public static void main(String[] args) throws Exception {
Yaml yaml = new Yaml();
InputStream inputStream =
new FileInputStream("your location\\yml-file-name.yml");
Recipe recipe = yaml.loadAs(inputStream,Recipe.class);
System.out.println("recipe = " + recipe);
}
}
这篇关于如何将 YAML 文件解析为 Java 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!