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

前端 未结 3 1662
情书的邮戳
情书的邮戳 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:54

    You need to add a custom Constructor. However, in your case you don't want register an "item" or "item-list" tag.

    In effect, you want to apply Duck Typing to your Yaml. It's not super efficient, but there is a relatively easy way to do this.

    class YamlConstructor extends Constructor {
      @Override
      protected Object constructObject(Node node) {
    
        if (node.getTag() == Tag.MAP) {
            LinkedHashMap map = (LinkedHashMap) super
                    .constructObject(node);
            // If the map has the typeId and limit attributes
            // return a new Item object using the values from the map
            ...
        }
         // In all other cases, use the default constructObject.
        return super.constructObject(node);
    

提交回复
热议问题