有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

SnakeYaml中的java多态集合

我的意图是使用jackson创建类似JSON中的多态集合,也许可以借助于标记

我似乎无法正确配置它

我的yaml文件是:

!person
age: 27
job: dev
name: me
skills:
- !devSkill {
  description: 'software development',
  name: 安卓,
  language: java, c++
  years: 7
}
- !softSkill {
  description: 'good person',
  name: <3,
  reason: lots of NGO work
}
- !sportsSkill {
  description: 'racing legend',
  name: vrooom,
  championships: - San Marino 2012
                 - San Marino 2015
}

在代码中,哪一个会映射到具有(抽象?)的层次结构有描述和名字的BaseSkill和3个孩子:dev、soft和sports

我的问题是,我对SnakeYAML的文档理解不够,不允许这样做。我目前的选择是:

Constructor constructor = new Constructor(Person.class);
TypeDescription carDescription = new TypeDescription(Person.class);
                carDescription.putListPropertyType("skills", SportsSkill.class);
                carDescription.putListPropertyType("skills", SoftSkill.class);
                carDescription.putListPropertyType("skills", DevSkill.class);
                // Apparently the last is the winner here because it overrides
                constructor.addTypeDescription(carDescription);

Representer representer = new Representer();
                representer.addClassTag(Person.class, new Tag("!person"));
                representer.addClassTag(SoftSkill.class, new Tag("!Softkill"));
                representer.addClassTag(DevSkill.class, new Tag("!devSkill"));
                representer.addClassTag(SportsSkill.class, new Tag("!portsSkill"));

DumperOptions options = new DumperOptions();
                options.setPrettyFlow(true);
Yaml yaml = new Yaml(constructor, representer, options);

错误在以下行中:

E/YAML﹕ Can't construct a java object for tag:yaml.org,2002:app.yamlmodel.Person; exception=Cannot create property=skills for JavaBean=Person(name=me, job=dev, age=27, skills=null); null; Can't construct a java object for !sportSkill; exception=Invalid tag: !sportSkill
    in "<reader>", line 1, column 1:
    name: me
    ^

共 (1) 个答案

  1. # 1 楼答案

    这个帖子已经过时了,但我找到了一个解决方案,希望它仍然能帮助别人。 你的错误是,你应该把标签和类型描述符添加到构造函数中,然后让SnakeYaml找出对象结构。 就你而言:

    Constructor constructor = new Constructor(Person.class);
    constructor.addTypeDescription(new TypeDescription(SoftSkill.class, new Tag("!softkill"));
    constructor.addTypeDescription(new TypeDescription(DevSkill.class, new Tag("!devkill"));
    constructor.addTypeDescription(new TypeDescription(SportsSkill.class, new Tag("!sportskill"));
    

    你没有提到你使用的SnakeYaml版本,但我使用的是1.16