0
---
university: scsb
country: us

Entities:
 !Entity 
   name: john
   subjects:
    -math
    -English
    -C++
 !Entity
   name: mary
   subjects:
    -science
    -French

我正在尝试将上述文件加载到地图中,实体部分下的数据将映射到实体对象的集合。这是一个正确的 yaml 语法,因为我得到 yaml 解析器错误。

4

1 回答 1

1

我在以下方面有更多的运气:

---
university: scsb
country: us

Entities: {
 !Entity {
   name: john,
   subjects:
    -math
    -English
    -C++
 },
 !Entity {
   name: mary,
   subjects:
    -science
    -French
 }
}

这是使用 SnakeYAML 的自定义标签 (!dice) 的示例。完整的例子在这里。它来自SnakeYAML 文档

class DiceConstructor extends SafeConstructor {
    public DiceConstructor() {
        this.yamlConstructors.put(new Tag("!dice"), new ConstructDice());
    }

    private class ConstructDice extends AbstractConstruct {
        public Object construct(Node node) {
            String val = (String) constructScalar((ScalarNode) node);
            int position = val.indexOf('d');
            Integer a = new Integer(val.substring(0, position));
            Integer b = new Integer(val.substring(position + 1));
            return new Dice(a, b);
        }
    }
}


@SuppressWarnings("unchecked")
public void testConstructor() {
    Yaml yaml = new Yaml(new DiceConstructor());
    Object data = yaml.load("{initial hit points: !dice '8d4'}");
    Map<String, Dice> map = (Map<String, Dice>) data;
    assertEquals(new Dice(8, 4), map.get("initial hit points"));
}
于 2013-02-23T02:53:26.587 回答