包含对象列表的SnakeYaml反序列化类 [英] SnakeYaml Deserialise Class containing a List of Objects

查看:305
本文介绍了包含对象列表的SnakeYaml反序列化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用snakeyaml将下面的YAML反序列化到下面的域模型中,但是我一直在获取java.lang.ClassCastException:java.util.LinkedHashMap无法转换为ConfigurableThing.

I'm trying to use snakeyaml to deserilise the below YAML into the domain model below, however I keep getting java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to ConfigurableThing.

请注意,我能够成功地反序列化单个ConfigurableThing,只有在尝试反序列化遇到问题的ConfigurableThings列表时,才可以.

Note I am able to successfully deserialise a single ConfigurableThing, it's only when trying to deserialise the list of ConfigurableThings that I run into issues.

要反序列化的代码

File file = new File(classLoader.getResource("config.yml").getFile());

        try(InputStream in = new FileInputStream(file)){
            Yaml yaml = new Yaml();
            Configuration config = yaml.loadAs(in,Configuration.class);
        }

YAML

things:
 - type: TYPE1
   name: foo
   value: 2.00
 - type: TYPE2
   name: bar
   value 8.00

模型

public final class Config {

    private List<ConfigurableThing> things;

    //Getter and Setter

}

public final class ConfigurableThing {

    private Type type;

    private String name;

    private BigDecimal value;

    //Getters and Setters
}

public enum Type {
    TYPE1,TYPE2
}

推荐答案

您没有显示用于加载YAML的代码,但是您的问题可能是您没有正确注册收集类型.试试这个:

You don't show the code you use to load your YAML, but your problem is probably that you did not register the collection type properly. Try this:

Constructor constructor = new Constructor(Config.class);
TypeDescription configDesc = new TypeDescription(Config.class);
configDesc.putListPropertyType("things", ConfigurableThing.class);
constructor.addTypeDescription(configDesc);
Yaml yaml = new Yaml(constructor);
Config config = (Config) yaml.load(/* ... */);

您需要执行此操作的原因是类型擦除– SnakeYaml无法在运行时确定List接口的通用参数.因此,您需要告诉它将列表项构造为ConfigurableThing;如果不这样做,将构造一个HashMap.这是您在错误消息中看到的.

The reason why you need to do this is type erasure – SnakeYaml cannot determine the generic parameter of the List interface at runtime. So you need to tell it to construct the list items as ConfigurableThing; if you do not, a HashMap will be constructed. This is what you see in the error message.

这篇关于包含对象列表的SnakeYaml反序列化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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