简体   繁体   English

如何将YAML文件解析为Java类

[英]How to parse YAML file to a Java class

I have a class Recipe that represents this YAML block: 我有一个代表此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;
}

Is there a way to parse this YAML to Recipe class without creating other classes or doing some tricks? 有没有一种方法可以将这个YAML解析为Recipe类,而无需创建其他类或进行一些技巧?

Firs of all, you have to include SnakeYML as dependency in maven pom.xml. 首先,您必须将SnakeYML作为依赖项包含在maven pom.xml中。 I provide below the maven dependency for snakeyml. 我在下面提供了pythonyml的Maven依赖项。

<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. 如果您不使用Maven,则可以从以下链接下载jar文件。 http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar

I modified your yml file bit to make it work. 我修改了您的yml文件以使其正常工作。 Find below the structure of yml file. 在yml文件的结构下面找到。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM