【问题标题】:How to simplify my yaml structure for better readability in java如何简化我的 yaml 结构以获得更好的 Java 可读性
【发布时间】:2021-09-03 12:06:35
【问题描述】:

如果我有以下yaml结构,如何在java中有效地读取它?目前,我正在阅读

xmas-fifth-day:
   calling-birds: 
     value: four
   partridges:
     count: 1
     value: "a pear tree"
   turtle-doves: 
     value: two


Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("src/main/resources/customer.yaml"));
Map<String, Object> data = yaml.load(inputStream);

LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, String>>> lhm = (LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, String>>>) data.get("xmas-fifth-day");

由于我使用了 3 级 hashmap,只是为了便于阅读,我想知道是否有这个 yaml 结构的简化版本可以在 java 中以较少嵌套的 LHM 方式读取?

编辑:我不想在这里添加 POJO,因为在我的用例中配置是动态的,任何人都可以添加任何配置,并且代码应该可以在不编辑 java 类的情况下工作。

【问题讨论】:

    标签: java nested yaml linkedhashmap


    【解决方案1】:

    看起来您正在使用 SnakeYAML,因此您可以定义自定义类型:

    public class XmasFifthDay {
      private CallingBirds callingBirds;
      private Partridges partridges;
      private TurtleDoves turtle-doves;
      // getters and setters
    }
    
    public class CallingBirds {
      private String value;
      // getters and setters
    }
    
    // other classes: Partridges, TurtleDoves
    

    然后加载它:

    XmasFifthDay data = yaml.load(inputStream);
    

    也许CallingBirdsPartridgesTurtleDoves 可能是具有countvalue 字段的单个类,但您提供的示例不是很清楚。

    【讨论】:

    • 我不想定义自定义类型,因为配置的值可以更改为可以添加或删除更多内容。所以用例让它变得灵活,让代码在不接触它的情况下工作。
    【解决方案2】:

    在我看来,杰克逊有更好的选择:

            Yaml yaml = new Yaml();
            InputStream inputStream = new FileInputStream(new File("test.yml"));
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
            final JsonNode jsonNode = mapper.readValue(inputStream, JsonNode.class);
            System.out.println(jsonNode.toPrettyString());
    
    

    输出将是:

    {
      "xmas-fifth-day" : {
        "calling-birds" : {
          "value" : "four"
        },
        "partridges" : {
          "count" : 1,
          "value" : "a pear tree"
        },
        "turtle-doves" : {
          "value" : "two"
        }
      }
    }
    
    System.out.println(jsonNode.get("xmas-fifth-day"));
    
    {"calling-birds":{"value":"four"},"partridges":{"count":1,"value":"a pear tree"},"turtle-doves":{"value":"two"}}
    

    您还可以使用 TyperReference 获得 String 和 JsonNode 的映射

    inputStream = new FileInputStream(new File("test.yml"));
            final Map<String,JsonNode>  map = mapper.readValue(inputStream, new TypeReference<Map<String, JsonNode>>() {});
            System.out.println(map.get("xmas-fifth-day"));
    

    输出是:

    {"calling-birds":{"value":"four"},"partridges":{"count":1,"value":"a pear tree"},"turtle-doves":{"value":"two"}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多