猿问

如何将 YAML 文件解析为 Java 类

我有一个Recipe代表这个 YAML 块的类:


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 类?


一只斗牛犬
浏览 283回答 1
1回答

富国沪深

首先,您必须将 SnakeYML 作为依赖项包含在 maven pom.xml 中。我在下面提供了 snakeyml 的 Maven 依赖项。<dependency>&nbsp; &nbsp; <groupId>org.yaml</groupId>&nbsp; &nbsp; <artifactId>snakeyaml</artifactId>&nbsp; &nbsp; <version>1.21</version></dependency>如果您不使用 Maven,则可以从以下链接下载 jar 文件。 http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar我修改了你的 yml 文件位以使其工作。在下面找到 yml 文件的结构。id: Ex1uses:&nbsp; Database: ["D1", "D2"]&nbsp; MetaFeature: ["M1", "M2"]&nbsp; Algorithm: ["A1", "A2"]&nbsp; Config: ["C1", "C4"]让我为您提供有效的代码。import java.util.HashMap;import java.util.HashSet;public class Recipe {&nbsp; private String id;&nbsp; private HashMap<String, HashSet<String>> uses;&nbsp; public String getId() {&nbsp; &nbsp; return id;&nbsp; }&nbsp; public void setId(String id) {&nbsp; &nbsp; this.id = id;&nbsp; }&nbsp; public HashMap<String, HashSet<String>> getUses() {&nbsp; &nbsp; return uses;&nbsp; }&nbsp; public void setUses(HashMap<String, HashSet<String>> uses) {&nbsp; &nbsp; this.uses = uses;&nbsp; }&nbsp; @Override&nbsp; public String toString() {&nbsp; &nbsp; return "Recipe{" + "id='" + id + '\'' + ", uses=" + uses + '}';&nbsp; }}根据您的 Recipe 类测试代码。import org.yaml.snakeyaml.Yaml;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.Map;public class TestYml {&nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; Yaml yaml = new Yaml();&nbsp; &nbsp; InputStream inputStream =&nbsp; &nbsp; &nbsp; &nbsp; new FileInputStream("your location\\yml-file-name.yml");&nbsp; &nbsp; Recipe recipe = yaml.loadAs(inputStream,Recipe.class);&nbsp; &nbsp; System.out.println("recipe = " + recipe);&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答