在Jackson的单个文件中反序列化来自多个YAML文档的POJO [英] Deserialize POJOs from multiple YAML documents in a single file in Jackson

查看:473
本文介绍了在Jackson的单个文件中反序列化来自多个YAML文档的POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的YAML文件:

I have a YAML file that looks something like this:

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

我想用Jackson来反序列化文件中的所有文件,但是我没有看到使用普通文件的方法code> ObjectMapper 来做。 如果我使用 YAMLFactory 为我的文件创建解析器,我可以遍历所有标记,因此解析器显然能够处理多个文档 - 但是如何做我将它们绑在一起?看起来我的YAMLFactory创建的解析器只解析文件中的单个文档。

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.

我也试过创建一个YAMLParser直接使用 ObjectMapper#readValue(JsonParser,Class),但ObjectMapper耗尽整个YAMLParser来反序列化单个实例。

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.

推荐答案

这是多年之后,但值得指出的是,这是支持的。
杰克逊的语义略有不同,可能是因为它的JSON起源。这可以通过使用 MappingIterator来实现。 来自 ObjectMapper

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();

如果需要,用您自己的POJO替换 ObjectNode

Replace ObjectNode with your own POJOs if desired.

这篇关于在Jackson的单个文件中反序列化来自多个YAML文档的POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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