SnakeYaml Deserialise Class containing a List of Objects

笑着哭i 提交于 2019-12-11 06:19:31

问题


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.

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.

Code to deserialise

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

Model

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
}

回答1:


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(/* ... */);

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.



来源:https://stackoverflow.com/questions/42545091/snakeyaml-deserialise-class-containing-a-list-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!