YAMLJackson-数组的锚键

gdx19jrr  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(53)

我正在尝试将YAML文件解析为对象。
即使在线YAML解析器告诉我,它是解析的方式,我想,JacksonYAML解析器拒绝给予我想要的。
下面是YAML文件:

- nom: "service1"
  etats : &e1s1
    - nom: "e1"
      childs:
        - nom: "e2"
          childs:
            - nom: "e3"
              childs:
              - &a
                nom: "e5"
        - nom: "e4"
          childs:
            - <<: *a

字符串
在线YAML解析器告诉我“e4”和“e3”有“e5”作为子元素。
然而,当我尝试用Jackson解析它时,我得到了以下错误:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "<<" (class Etat), not marked as ignorable (4 known properties: "dependsOnAnotherService", "nom", "hasToken", "childs"])
at [Source: (File); line: 13, column: 21] (through reference chain: java.lang.Object[][0]->Service["etats"]->java.util.ArrayList[0]->Etat["childs"]->java.util.ArrayList[1]->Etat["childs"]->java.util.ArrayList[0]->Etat["<<"])


所以,我想知道是否有人有办法做到这一点,Jackson会接受它?

更新

我也试过这个:

- nom: "service1"
  etats : &e1s1
    - nom: "e1"
      childs:
        - nom: "e2"
          childs:
            - nom: "e3"
              childs:
              - &a
                nom: "e5"
        - nom: "e4"
          childs:
            - *a


但是得到:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `Etat` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('a')
at [Source: (File); line: 13, column: 15] (through reference chain: java.lang.Object[][0]->Service["etats"]->java.util.ArrayList[0]->Etat["childs"]->java.util.ArrayList[1]->Etat["childs"]->java.util.ArrayList[0])

m4pnthwp

m4pnthwp1#

<<不是YAML的核心特性,只是作为过时的YAML 1.1的可选标记指定的(参见here)。因此,Jackson完全有权不支持它。相反,它试图将<<解析为字段名称,这显然是失败的,因为没有这样的字段。
第二种方法更合适,因为它只使用了核心的YAML功能。您得到的错误是因为Jackson是known not to support anchors and aliases,并且错误地将别名*a视为String而不是解析它。
现在你在你的问题中称Jackson为一个 *YAML解析器 *,它不是。它只是使用SnakeYaml作为解析器。SnakeYaml可以自己将YAML加载到用户定义的类中,所以你最好直接使用SnakeYaml API . Afaik它可以正确处理别名。

相关问题