获取Integer []而不是ArrayList< Integer>.从YAML文件 [英] Get Integer[] instead of ArrayList<Integer> from YAML file

查看:150
本文介绍了获取Integer []而不是ArrayList< Integer>.从YAML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析YAML文件

I am parsing a YAML file

Props:
  Prop1 : [10, 22, 20]
  Prop2 : [20, 42, 60]

这给了我Map<String, Map<String, ArrayList<Integer>>> 我想得到Map<String, Map<String, Integer[]>> 我不想在读取文件的代码中转换List<Integer> to Integer[].我可以更改YAML文件中的某些内容吗?

This gives me Map<String, Map<String, ArrayList<Integer>>> I would like to get Map<String, Map<String, Integer[]>> I do not want to convert List<Integer> to Integer[] in the code that reads the file. Can I change something in my YAML file?

推荐答案

与我的其他答案相反,该主题着重于更改YAML文件.但是,您还需要添加一些Java代码来告诉SnakeYaml如何加载您使用的标签.

In contrast to my other answer, this one focuses on changing the YAML file. However, you also need to add some Java code to tell SnakeYaml how to load the tag you use.

您可以在YAML序列中添加标签:

You could add tags to the YAML sequences:

Props:
  Prop1 : !intarr [10, 22, 20]
  Prop2 : !intarr [20, 42, 60]

在加载前需要先向SnakeYaml注册:

This need to be registered with SnakeYaml before loading:

public class MyConstructor extends Constructor {
    public MyConstructor() {
        this.yamlConstructors.put(new Tag("!intarr"),
                                  new ConstructIntegerArray());
    }

    private class ConstructIntegerArray extends AbstractConstruct {
        public Object construct(Node node) {
            final List<Object> raw = constructSequence(node);
            final Integer[] result = new Integer[raw.size()];
            for(int i = 0; i < raw.size(); i++) {
                result[i] = (Integer) raw.get(i);
            }
            return result;
        }
    }
}

您可以这样使用它:

Yaml yaml = new Yaml(new MyConstructor());
Map<String, Map<String, Integer[]>> content =
    (Map<String, Map<String, Integer[]>>) yaml.load(myInput);

这篇关于获取Integer []而不是ArrayList&lt; Integer&gt;.从YAML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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