'How can I avoid a ClasstCastException when when deserializing a nested Map containing a custom class using SnakeYaml?
I am attempting to use SnakeYaml to deserialize an object into the correct Java object in Spring boot.
My Yaml looks like this:
workflows:
flow1:
firstPage:
nextPages:
- pageName: secondPage
secondPage:
nextPages:
- pageName: thirdPage
flow2:
firstPage:
nextPages:
- pageName: fancyPage
fancyPage:
nextPages:
The object this yaml represents is: Map<String flowName, Map<String pageName, Class PageConfiguration>>
This data structure is a field (workflows) in class I have defined called ApplicationConfiguration.
PageConfiguration is a custom class that contains a single field of a custom class NextPage which is another class that contains a single field String pageName.
The object was originally just Map<String, PageConfiguration> and that deserialized fine, but I wanted to extend the functionality to allow for multiple flows hence the new Map<String, Map<String, PageConfiguration>> data structure.
The new nested data structure is throwing an ClassCastException error, cannot cast LinkedHashMap to PageConfiguration when I try to access the values contained within.
Here is my deserialization code: (note configPath is the correct path to the YAML file)
public ApplicationConfiguration getObject() {
ClassPathResource classPathResource = new ClassPathResource(configPath);
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setAllowDuplicateKeys(false);
loaderOptions.setMaxAliasesForCollections(Integer.MAX_VALUE);
loaderOptions.setAllowRecursiveKeys(true);
Yaml yaml = new Yaml(new Constructor(ApplicationConfiguration.class), new Representer(),
new DumperOptions(), loaderOptions);
ApplicationConfiguration appConfig = null;
try {
appConfig = yaml.load(classPathResource.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return appConfig;
}
And how I am attempting to access it when I get the ClassCastException:
public PageWorkflowConfiguration getPageWorkflow(String flowName, String pageName) {
return this.workflows.get(flowName).get(pageName);
}
It seems like the additional layer of nesting caused SnakeYaml to fail to deserialize correctly causing the ClassCastException error, cannot cast LinkedHashMap to PageConfiguration?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
