Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize POJOs from multiple YAML documents in a single file in Jackson

Tags:

java

yaml

jackson

I have a YAML file that looks something like this:

---
name: Sam
tags:
    -   Dev
    -   Java
----
name: Bob
tags:
    -   PM

I'd like to use Jackson to deserialize all documents from the file, but I don't see a way to use a normal ObjectMapper to do it. If I use the YAMLFactory to create a parser for my file I can step through all tokens, so the parser is obviously capable of dealing with multiple documents - but how do I tie them together? Looks like the parser created by my YAMLFactory only parses a single document out of the file.

I've also tried creating a YAMLParser directly and using ObjectMapper#readValue(JsonParser, Class), but the ObjectMapper exhausts the entire YAMLParser to deserialize a single instance.

like image 981
Dathan Avatar asked Aug 09 '14 19:08

Dathan


1 Answers

This is years later but it's worth pointing out that this is supported. The Jackson semantics are slightly different, probably due to it's JSON origins. This can be achieved by using the MappingIterator from ObjectMapper.

YAMLFactory yaml;
ObjectMapper mapper;

YAMLParser yamlParser = yaml.createParser("file-with-multiple-docs.yaml")
List<ObjectNode> docs = mapper
      .readValues<ObjectNode>(yamlParser, new TypeReference<ObjectNode> {})
      .readAll();

Replace ObjectNode with your own POJOs if desired.

like image 87
zcourts Avatar answered Sep 22 '22 09:09

zcourts