【问题标题】:Jackson - Pass Values to JsonDeserializerJackson - 将值传递给 JsonDeserializer
【发布时间】:2014-11-12 04:28:20
【问题描述】:

我有一个现有的类层次结构,如下所示:

public interface Service {
  String getId();
  String getName();
}

public class FooTask extends AbstractTask {
  private final static ObjectMapper JSON_MAPPER = new ObjectMapper();

  static {
    JSON_MAPPER.registerModule(new SimpleModule().addDeserializer(Result.class, new ResultDeserializer());
  }

  public FooTask(Service service) {
    super(service);
  }

  @Override public Result call() throws Exception {
     InputStream json = <... execute some code to retrieve JSON ...>
     Result result = JSON_MAPPER.readValue(json, Result.class);
  }

  private static class ResultDeserializer {
    @Override public Result deserialize(JsonParser parser, DeserializationContext ctx) throws IOException {

      //
      // Need to access service#getId() down here... but we're in a static nested class 
      // and I don't know how to access it. Is there some way to pass that info via the DeserializationContext?
      //

      <... Deserialization logic ...>
    }
  }
}

我需要在反序列化时将一些信息传递给反序列化器,但我找不到在反序列化时将一些上下文信息传递给反序列化器的方法。这可能吗?如果是这样,怎么做?我宁愿不必在每次实例化 FooTask 或调用 #call() 方法时都分配一个新的 ObjectMapper。

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    所以我想出了一个解决方案......不知道它是否是理想的解决方案,但它是一个解决方案 - 基本上我首先创建一个 InjectableValues 实例:

    private InjectableValues newInjectableValues() {
      return new InjectableValues.Std()
        .addValue("providerId", service.getId())
    }
    

    然后我从 ObjectMapper 获得一个新的 ObjectReader 实例并使用它来执行反序列化:

    JSON_MAPPER.reader(newInjectableValues()).withType(Result.class).readValue(inputStream)
    

    在实际的 Deserializer 中我使用这种方法来检索 InjectableValues 提供的值:

    ctx.findInjectableValue("providerId", null, null);
    

    【讨论】:

    • 你拯救了我的一天。搜索了很多关于如何做到这一点,你的解决方案就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2015-12-09
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多