如何将YAML文件解析为Java类

时间:2019-06-01 17:57:31

标签: java parsing yaml

我有一个表示该YAML块的类Recipe

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类而不创建其他类或进行一些技巧?

1 个答案:

答案 0 :(得分:2)

首先,您必须将SnakeYML作为依赖项包含在maven pom.xml中。我在下面提供了pythonyml的Maven依赖项。

<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

我修改了您的yml文件以使其正常工作。在yml文件的结构下面找到。

id: Ex1
uses:
  Database: ["D1", "D2"]
  MetaFeature: ["M1", "M2"]
  Algorithm: ["A1", "A2"]
  Config: ["C1", "C4"]

让我为您提供有效的代码。

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 + '}';
  }
}

根据您的食谱类测试代码。

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);
  }
}