使用snakeYaml在根目录中解析带有映射的YAML文档 [英] Parsing a YAML document with a map at the root using snakeYaml

查看:307
本文介绍了使用snakeYaml在根目录中解析带有映射的YAML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将YAML文档读取到自定义对象的地图(而不是默认情况下snakeYaml执行的地图)。所以这个:

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:
  typeID: 8
  limit: 100

将被加载到看起来像像这样:

Would be loaded to a map which looks like this:

Map<Integer, Item>

其中Item为:

class Item {
    private Integer typeId;
    private Integer limit;
}

我找不到办法用snakeYaml做到这一点,我无法'找到一个更好的任务库。

I could not find a way to do this with snakeYaml, and I couldn't find a better library for the task either.

该文档仅包含嵌套在其他对象中的maps / collections的示例,以便您可以执行以下操作:

The documentation only has examples with maps/collections nested inside other objects, so that you can do the following:

    TypeDescription typeDescription = new TypeDescription(ClassContainingAMap.class);
    typeDescription.putMapPropertyType("propertyNameOfNestedMap", Integer.class, Item.class);
    Constructor constructor = new Constructor(typeDescription);
    Yaml yaml = new Yaml(constructor);
    /* creating an input stream (is) */
    ClassContainingAMap obj = (ClassContainingAMap) yaml.load(is);

但是,当它位于文档的根目录时,如何定义Map格式?

But how do I go about defining the Map format when it is at the root of the document?

推荐答案

您需要添加自定义构造函数。但是,在您的情况下,您不希望注册item或item-list标记。

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

实际上,您想申请 Duck Typing 给你的Yaml。它不是超级高效的,但有一种相对简单的方法可以做到这一点。

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<String, Object> map = (LinkedHashMap<String, Object>) 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);

这篇关于使用snakeYaml在根目录中解析带有映射的YAML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆