Michael Böckling
Michael Böckling

Reputation: 7872

Use custom object in Jackson constructor

Is there a way to provide the Jackson Deserializer with a default value from "the outside" (e.g. DI container) that it will use when deserializing an object, in this case tagRegistry?

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

I couldn't find an easy way to do this.

Upvotes: 0

Views: 177

Answers (1)

Sebastian Heikamp
Sebastian Heikamp

Reputation: 976

You could try @JacksonInject. Add this member to the ExtractionRule class:

@JacksonInject("tagRegistry")
private TagRegistry tagRegistry;

And inject the tagRegistry to the ObjectMapper before deserialization:

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

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

I haven't tried using it in a constructor, not sure if that works. You can find further examples here:

Upvotes: 1

Related Questions