Parsing a YAML document with a map at the root using snakeYaml

前端 未结 3 1669
情书的邮戳
情书的邮戳 2021-01-04 13:34

I want to read a YAML document to a map of custom objects (instead of maps, which snakeYaml does by default). So this:

19:
  typeID: 2
  limit: 300
20:
  typ         


        
3条回答
  •  醉酒成梦
    2021-01-04 13:58

    Here is what I did for a very similar situation. I just tabbed my whole yml file over one tab and added a map: tag to the top. So for your case it would be.

    map:
      19:
        typeID: 2
        limit: 300
      20:
        typeID: 8
        limit: 100
    

    And then create a static class in your class that reads this file like follows.

    static class Items {
        public Map map;
    }
    

    And then to read your map just use.

    Yaml yaml = new Yaml(new Constructor(Items));
    Items items = (Items) yaml.load();
    Map itemMap = items.map;
    

    UPDATE:

    If you don't want to or cannot edit your yml file you could just do the above transform in code while reading the file with something like this.

    try (BufferedReader br = new BufferedReader(new FileReader(new File("example.yml")))) {
        StringBuilder builder = new StringBuilder("map:\n");
        String line;
        while ((line = br.readLine()) != null) {
            builder.append("    ").append(line).append("\n");
        }
    
        Yaml yaml = new Yaml(new Constructor(Items));
        Items items = (Items) yaml.load(builder.toString());
        Map itemMap = items.map;
    }
    

提交回复
热议问题