ObjectMapper 必须使用 JSON 文件未提供的参数调用构造函数

ObjectMapper has to call Constructor with Arguments not provided by JSON file

我的目标是在我们的全局事件代理和 Spring 的 ApplicationEvent 系统之间编写某种桥梁。

消息代理以 JSON 格式提供消息。我的想法是

public class ExternalApplicationEvent extends ApplicationEvent {
   ...
   // e.g @JsonPropert private String name;
}

然后调用

objectMapper.readValue(brokerMessage, ExternalApplicationEvent.class);

问题是,ApplicationEvent 需要在构造时间 上设置源 ,它应该是 ExternalEventBridge 的实例,用于不属于 JSON-文档的明显原因。

我发现如何向 JSON 添加属性,这些属性不是 @JsonAppend 序列化对象的一部分,但我还没有找到适合我方向的解决方案,传递参数class.

的构造函数

我最后的想法是使用

objectMapper.readerForUpdating(new ExternalApplicationEvent(theSource)).readValue(message)

但不知何故这并没有 填充 我的事件。

如果我添加构造函数

public ExternalApplicationEvent() {
  super(new Object());
}

并使用 objectMapper.readValue(message, ExternalApplicationEvent.class),通过字段注入正确填充对象。此外,添加二传手也无济于事。

我现在通过将数据与 ApplicationEvent 分开解决了这个问题:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // Don't detect `getSource` from ApplicationEvent
public class ExternalApplicationEvent extends ApplicationEvent {

    // I might use @JsonUnwrapped probably, but since I have to create setters
    // and getters anyway...
    private ExternalApplicationEventData p = new ExternalApplicationEventData();

    public ExternalApplicationEvent(Object source, ExternalApplicationEventData data) {
        super(source);
        p = data;
    }

    @JsonGetter("name")
    public String getName() { return p.name; }

    public void setName(String name) { p.name = name; }

    public static class ExternalApplicationEventData {

        @JsonCreator
        private ExternalApplicationEventData() {} // Make creation only possible by parsing or from the ExternalApplicationEvent class

        @JsonProperty
        private String name;

        ...
    }
}

然后创建事件

var data = objectMapper.readValue(message, ExternalApplicationEvent.ExternalApplicationEventData.class);
var event = new ExternalApplicationEvent(this, data);