How to parse YAML file to a Java class

随声附和 提交于 2021-02-11 14:36:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!