Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SnakeYaml - ClassCastException when deserialising into a map of string and custom objects

I was trying to use SnakeYaml to create a map of string and objects in Java.

There is a Person.java class for storing information about a person. I wanted to read the information about each person from a yaml file and store it in a map with the key being the person name and the value being the Person object. ie. For every person name, a person object has to be created and added to the map.

EDIT: The YAML deserialisation should create a Map<String, Person>

Below are the contents of each file:

YAML file:

PersonName1: 
  value1: foo1
  value2: bar1
  value3: foobar1

PersonName2:
  value1: foo2
  value2: bar2
  value3: foobar2

Person.java

public class Person {
    public String value1;
    public String value2;
    public String value3;
}

Main.java

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(new File("SampleYamlFile.yml"));
        Yaml yaml = new Yaml();

        Map<String, Person> persons = (Map<String, Person>) yaml.load(inputStream);
        for(String key : persons.keySet()) {
            System.out.println("key = " + key);
            Person person = persons.get(key);
            System.out.println("person = " + person);
        }
    }
}

The map gets created without any errors. The key also gets printed. But when I try to access the value of the key, I get a ClassCastException

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Person

Is this type of deserialisation not supported by SnakeYaml? Any help on why this problem occurs and how this problem can be solved is much appreciated.

like image 415
Balasubramanian Avatar asked Nov 11 '22 00:11

Balasubramanian


1 Answers

Change this:

Yaml yaml = new Yaml();

to:

Yaml yaml = new Yaml(new Constructor(Person.class));

Here is a good example how to work with SnakeYaml: https://aqaexplorer.com/2019/12/10/parsing-yaml-with-snake-yaml/

like image 56
v.ryabchuk Avatar answered Nov 14 '22 21:11

v.ryabchuk