问题
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;
}
Is there a way to parse this YAML to Recipe class without creating other classes or doing some tricks?
回答1:
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>
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
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);
}
}
来源:https://stackoverflow.com/questions/56409143/how-to-parse-yaml-file-to-a-java-class