【问题标题】:Use custom object in Jackson constructor在 Jackson 构造函数中使用自定义对象
【发布时间】:2020-02-24 13:12:29
【问题描述】:

有没有办法为 Jackson Deserializer 提供来自“外部”(例如 DI 容器)的默认值,它将在反序列化对象时使用,在本例中为 tagRegistry?

  @JsonCreator
  public ExtractionRule(@JsonProperty("id") String id, 
                        TagRegistry tagRegistry) {
    this.id = id;
    this.tagRegistry = tagRegistry;
  }

我找不到一个简单的方法来做到这一点。

【问题讨论】:

  • 这样的吗? @JsonDeserialize(using = CustomDeserializer.class) 公共类 CustomClass { ... }

标签: java jackson


【解决方案1】:

你可以试试@JacksonInject。将此成员添加到 ExtractionRule 类:

@JacksonInject("tagRegistry")
private TagRegistry tagRegistry;

并在反序列化之前将tagRegistry注入到ObjectMapper中:

 InjectableValues.Std injectableValues = new InjectableValues.Std();
 injectableValues.addValue("tagRegistry", tagRegistry);

 ObjectMapper objectMapper = new ObjectMapper();
 objectMapper.setInjectableValues(injectableValues);

我没有尝试在构造函数中使用它,不确定是否有效。 您可以在此处找到更多示例:

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多