【问题标题】:How to read from YAML file in java?如何在 java 中读取 YAML 文件?
【发布时间】:2020-11-09 08:40:45
【问题描述】:

我有这样的 YAML 文件..

Product:
 ProductA:
  Suite:
    SuiteName_A:
      Environment_1: ["A","B","C"]
      Environment_2: ["X","Y","Z"]
    SuiteName_B:
      Environment_1: ["E","F","G"]
      Environment_2: ["K","L","M"]
 ProductB:
  Suite:
    SuiteName_K:
      Environment_1: ["A1","B2","C3"]
      Environment_2: ["X1","Y1","Z1"]

已编辑---- 正如我在一些阅读文章中所读到的那样,我创建了一些课程,这里是我想出的......

环境类

    package Configuration;

import java.util.ArrayList;

public class Environment {
    private ArrayList<String> Environment_1;
    private ArrayList<String> Environment_2;

    public ArrayList<String> getEnvironment_1() {
        return Environment_1;
    }

    public void setEnvironment_1(ArrayList<String> Environment_1) {
        this.Environment_1 = Environment_1;
    }

    public ArrayList<String> getEnvironment_2() {
        return Environment_2;
    }

    public void setEnvironment_2(ArrayList<String> Environment_2) {
        this.Environment_1 = Environment_2;
    }
}

西装名称类

    package Configuration;

import java.util.HashMap;

public class SuiteNames {
    private HashMap<String,Environment> Suite;

    public HashMap<String, Environment> getSuite() {
        return Suite;
    }

    public void setSuite(HashMap<String, Environment> suite) {
        Suite = suite;
    }
}

产品类别

    package Configuration;

import java.util.HashMap;

public class Product {
    private HashMap<String,SuiteNames> Product;

    public HashMap<String, SuiteNames> getProduct() {
        return Product;
    }

    public void setProduct(HashMap<String, SuiteNames> product) {
        this.Product = product;
    }
}

主类

    package Configuration;

import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class DbClass {

    public static void main(String[] args) throws FileNotFoundException {
        Yaml yaml = new Yaml();
        InputStream inputStream = new FileInputStream("path");
        System.out.println(inputStream);
        Product product = yaml.loadAs(inputStream,Product.class);
        System.out.println(product.getProduct());
    }
}

这会出现以下错误:

     Exception in thread "main" Cannot create property=Product for JavaBean=Configuration.Product@4c98385c
 in 'reader', line 1, column 1:
    Product:
    ^
Unable to find property 'Product' on class: Configuration.Product
 in 'reader', line 2, column 3:
      Check-in:
      ^

    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:270)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:149)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:309)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:216)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:205)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructDocument(BaseConstructor.java:164)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:148)
    at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:525)
    at org.yaml.snakeyaml.Yaml.loadAs(Yaml.java:519)
    at Configuration.DbClass.main(DbClass.java:17)
Caused by: org.yaml.snakeyaml.error.YAMLException: Unable to find property 'Product' on class: Configuration.Product
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:159)
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:148)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.getProperty(Constructor.java:287)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:208)
    ... 9 more

我想获取环境名称列表并将其存储在列表中。我知道使用杰克逊 api。但我不知道如何将这些数据映射到类。 我正在使用 servlet,在 servlet 内部我想要一个 java 方法来获取字符串列表。

【问题讨论】:

标签: java yaml snakeyaml


【解决方案1】:

YAML 有一个推荐的 Java 库列表: SnakeYAMLYamlBeanseo-yaml

其中最广泛使用的可能是 SnakeYAML。 Baeldung在这里有一个非常容易理解的教程:https://www.baeldung.com/java-snake-yaml

[编辑以解决新代码并在 OP 编辑​​中输出]:

您使用的格式和命名约定也存在一些问题。在你的 yaml 文件中,任何列表都需要[括号],实例变量需要是驼峰式,任何字符串都需要用引号括起来(包括字符串 HashMap 键):

products:
  "ProductA":
    suite:
      "SuiteName_A":
        environment_1: ["A","B","C"]
        environment_2: ["X","Y","Z"]
      "SuiteName_B":
        environment_1: ["E","F","G"]
        environment_2: ["K","L","M"]
  "ProductB":
    suite:
      "SuiteName_K":
        environment_1: ["A1","B2","C3"]
        environment_2: ["X1","Y1","Z1"]

您应该尝试在您的 bean 命名约定中匹配它。此外,您的第二个设置者需要设置 Environment_2 而不是 Environment_1。这是您的实体类的外观。

环境

package Configuration;

import java.util.ArrayList;

public class Environment {
    private ArrayList<String> environment_1;
    private ArrayList<String> environment_2;

    public ArrayList<String> getEnvironment_1() {
        return environment_1;
    }

    public void setEnvironment_1(ArrayList<String> environment_1) {
        this.environment_1 = environment_1;
    }

    public ArrayList<String> getEnvironment_2() {
        return environment_2;
    }

    public void setEnvironment_2(ArrayList<String> environment_2) {
        this.environment_2 = environment_2;
    }
}

套房名称

package Configuration;

import java.util.HashMap;

public class SuiteName {
    private HashMap<String,Environment> suite;

    public HashMap<String, Environment> getSuite() {
        return suite;
    }

    public void setSuite(HashMap<String, Environment> suite) {
        suite = suite;
    }
}
package Configuration;

import java.util.HashMap;

public class Product {
    private HashMap<String, SuiteName> products;

    public HashMap<String, SuiteName> getProducts() {
        return products;
    }

    public void setProducts(HashMap<String, SuiteName> products) {
        this.products = products;
    }
}

编辑: 在您的主要方法中,您可能希望使用 yaml.load(inputStream) 来获取 HashMap 中的整个文件。根据您在评论中的问题,我添加了访问数据结构。

数据库类

package Configuration;

import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class DbClass {

    public static void main(String[] args) throws FileNotFoundException {
        Yaml yaml = new Yaml();
        InputStream inputStream = new FileInputStream("path.yml");
        System.out.println(inputStream);

        HashMap yamlMap = yaml.load(inputStream);
        for (Object o : yamlMap.entrySet()) {
            System.out.println(o);
        }
        // Access HashMaps and ArrayList by key(s)
        HashMap products = (HashMap) yamlMap.get("products");
        HashMap product = (HashMap) products.get("ProductA");
        HashMap suite = (HashMap) product.get("suite");
        HashMap suiteName = (HashMap) suite.get("SuiteName_B");
        ArrayList environment = (ArrayList) suiteName.get("environment_1");
        System.out.println(environment);
    }
}

【讨论】:

  • 嘿@JeffSchenck 尝试了这种方法并得到了错误。我已经编辑了问题并包含了类文件...请您查看一下...谢谢
  • 嗨@KoushikJ 我编辑了我的答案以解决您修改后的问题。
  • 嘿,杰夫...谢谢它的工作并得到如下结果
  • {Product=ProductA{={"SuiteName_A"={environment_1=["A","B","C"]}.....}}....现在给定Productname,suitename 和 enivireonment...我只想列出结果...您对此有什么想法...?
  • 没问题@KoushikJ。根据您的问题,我添加了访问数据结构。
【解决方案2】:

这是无效的 YAML:

      Environment_1: "A","B","C"

你需要做的

      Environment_1: ["A","B","C"]

那么,setter 的名字是错误的:

    public ArrayList<String> getEnvironment_1() {
        return Environment_1;
    }

    public void setINT(ArrayList<String> Environment_1) {
        this.Environment_1 = Environment_1;
    }

setter 必须命名为setEnvironment_1。这是因为 SnakeYAML 通过其 getter 和 setter 访问私有字段。

下一个问题是 YAML 中的名称以大写字母开头。 SnakeYAML 使用JavaBeans API 来发现属性,这将产生environment_1 作为属性名称,而不是Environment_1。您可以通过覆盖属性发现来解决此问题:

final PropertyUtils uppercaseUtils = new PropertyUtils() {
    @Override
    public Property getProperty(Class<? extends Object> type, String name) throws IntrospectionException {
        return super.getProperty(name.substring(0, 1). toLowerCase() + name. substring(1));
    }
}
final Constructor c = new Constructor(Product.class);
c.setPropertyUtils(uppercaseUtils);
Yaml yaml = new Yaml(c);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多