杰克逊 - 将值传递给JsonDeserializer [英] Jackson - Pass Values to JsonDeserializer

查看:764
本文介绍了杰克逊 - 将值传递给JsonDeserializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an existing class hierarchy that looks like this:

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。

I need to pass some information to the deserializer at deserialization time but I cannot find a way to pass some contextual information to the deserializer at deserialization time. Is this possible? If so, how? I would prefer to not have to allocate a new ObjectMapper every time the FooTask is instantiated or #call() method is invoked.

推荐答案

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

So I came up with a solution... no idea if it is the ideal solution, but it is a solution - basically I first create an instance of InjectableValues:

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

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

Then I get a new ObjectReader instance from the ObjectMapper and use that to perform the deserialization:

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

在实际的反序列化器中向下我使用这个检索InjectableValues提供的值的方法:

Down in the actual Deserializer I use this method to retrieve the values provided by the InjectableValues:

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

这篇关于杰克逊 - 将值传递给JsonDeserializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆