Java JacksonInject-class And Method Code Example

Here is an example of using the JacksonInject annotation from the org.codehaus.jackson.annotate package in the Apache Commons IO library to inject a value into a field of a Java class during serialization or deserialization with the Jackson JSON library:

import org.codehaus.jackson.annotate.JacksonInject;

public class MyClass {
    private String injectedValue;

    public String getInjectedValue() {
        return injectedValue;

    public void setInjectedValue(String injectedValue) {
        this.injectedValue = injectedValue;

In this example, the @JacksonInject annotation is used to indicate that the injectedValue field should be injected with a value during serialization or deserialization. The value to be injected can be set by passing an InjectableValues object to the ObjectMapper when deserializing or serializing the object.


public class Main {
    public static void main(String[] args) {
        MyClass myObject = new MyClass();

        InjectableValues inject = new InjectableValues.Std().addValue(String.class, "injectedValue", "Value to be injected");
        ObjectMapper mapper = new ObjectMapper().setInjectableValues(inject);

        String json = mapper.writeValueAsString(myObject);
        System.out.println("Serialized JSON: " + json);

        MyClass deserialized = mapper.readValue(json, MyClass.class);
        System.out.println("Injected value: " + deserialized.getInjectedValue());

In this example, the InjectableValues.Std().addValue(String.class, "injectedValue", "Value to be injected") creates an InjectableValues object that will inject the value "Value to be injected" into the injectedValue field when deserializing or serializing the object, and then we passed this object to the ObjectMapper via mapper.setInjectableValues(inject) to tell it to use that object for injecting values.