有 Java 编程相关的问题?

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

java Jackson:反序列化接口集(yml)的实例化子类

鉴于以下yml:

---
  commands:
    dev: !foo.bar.Baz {}

下一节课呢

public class PluginFile {
    private Map<String, Command> commands = new HashMap<String, Command>();
    public Map<String, Command> getCommands() {
        return commands;
    }
    public void setCommands(Map<String, Command> commands) {
        this.commands = commands;
    }

以及读取文件:

mapper.readValue(theFile, PluginFile.class);

错误结果:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of foo.bar.command.Command, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: C:\theFile.yml; line: 3, column: 10] (through reference chain: foo.bar.PluginFile["commands"]->java.util.LinkedHashMap["dev"])

这似乎意味着Jackson无法确定在Pluginfle上设置命令的具体实例。命令()。但是,该类型是由yml文件本身使用定义和创建的!福。酒吧DevCommand{}语法

我可以通过使用以下yaml来实现这一点:

---
  commands:
    dev: 
      type: foo.bar.Baz

然后注释贴图属性:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")

但是我真的想使用yaml Java文字语法


共 (1) 个答案

  1. # 1 楼答案

    基类Command需要有@JsonTypeInfo来指示它需要多态处理;如果是这样,Jackson将知道如何查找YAML内容所具有的类型标识符。如果foo.bar.Baz指定了一个类(即包foo.bar,类Baz),则应将类型包含指定为“类名”

    或者,您也可以为map属性指定@JsonTypeInfo。比如:

    public class PluginFile {
      @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS)
      private Map<String, Command> commands = new HashMap<String, Command>();
    }