使用Jackson的root名称前缀进行YAML的选择
我想使用Jackson和Jackson-Dataformat-Yaml将YAML文件列为Java对象。
YAML是
company:
product:
settings:
property: value
目标类是
@Getter @Setter
public class TargetObject {
private Map<String, String> settings;
}
进行挑选的代码,
TargetObject config =
new ObjectMapper(new YAMLFactory())
.readerFor(TargetObject.class)
.withRootName("company.product")
.readValue(yamlResource.getInputStream());
当执行此代码时,我会遵循异常:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name ('company') does not match expected ('company.product') for type `a.b.c.TargetObject`
没有第二个嵌套“产品”所有内容。在不触及YAML的情况下解决此问题有可能解决吗?我已经阅读了有关逃避点作为YAML键的之类的dots,例如“ [company.product]”
,但可悲的是,在我的用例中,这不是一个选择。
问候,Rokko
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您非常接近解决方案,问题出在您使用错误的
objectreader#withRootname
代码中的方法:相反,您必须使用
objectReader#at
选择您对适当“/company/product”的YAML部分的方法,以获得预期结果:
You are very close to the solution, the problem stands in the fact you are using the wrong
ObjectReader#withRootName
method in your code:Instead you have to use the
ObjectReader#at
method to select the yaml part you are interested with the appropriate"/company/product"
path to obtain the expected result: