Aftab
Aftab

Reputation: 2963

How to bypass @JsonIgnore annotation?

I am trying to create a rest end point and using Swagger as UI representation. The pojo which I'm using it has a variable annotated with @JsonIgnore as shown below.

@JsonIgnore
private Map<String, Object> property = new HashMap<String, Object>(); 

Now, when I'm providing JSON (with property value) to this end point and trying to read its value it is coming out as null (due to @JsonIgnore).

pojoObj.getProperties(); //null

Is there any way if I can get property value without removing the @JsonIgnore annotation?

Upvotes: 2

Views: 1318

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

This can be achieved by utilizing Jackson's Mixin feature, where you create another class that cancels the ignore annotation. You can then "attach" the mixin to the ObjectMapper at run time:

This is the POJO I used:

public class Bean
{
    // always deserialized
    public String name;

    // ignored (unless...) 
    @JsonIgnore
    public Map<String, Object> properties = new HashMap<String, Object>();
}

This is the "other" class. It is just another POJO with the same property name

public class DoNotIgnore
{
    @JsonIgnore(false)
    public Map<String, Object> properties;
}

a Jackson Module is used to tie the bean to the mixin:

@SuppressWarnings("serial")
public class DoNotIgnoreModule extends SimpleModule
{
    public DoNotIgnoreModule() {
        super("DoNotIgnoreModule");
    }

    @Override
    public void setupModule(SetupContext context)
    {
        context.setMixInAnnotations(Bean.class, DoNotIgnore.class);
    }
}

Tying it all together:

public static void main(String[] args)
{
    String json = "{\"name\": \"MyName\","
            +"\"properties\": {\"key1\": \"val1\", \"key2\": \"val2\", \"key3\": \"val3\"}"
            + "}";

    try {
        ObjectMapper mapper = new ObjectMapper();
        // decide at run time whether to ignore properties or not
        if ("do-not-ignore".equals(args[0])) {
            mapper.registerModule(new DoNotIgnoreModule());
        }
        Bean bean = mapper.readValue(json, Bean.class);
        System.out.println(" Name: " + bean.name + ", properties " + bean.properties);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 5

Related Questions