Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflicting getter definitions for property in Jackson 2.2.3

Tags:

json

jackson

For simplicity here is a simple class:

class GetterMethodsObject {

    int id = 10;

    public int getId() {
        return id;
    }

    // @JsonIgnore
    public boolean isId() {
        return true;
    }
}

Serializing this object should give:

{"id":10}

as there is public getter method. Usage example:

mapper=new ObjectMapper();
mapper.writeValueAsString(object);

But I am getting exception:

com.fasterxml.jackson.databind.JsonMappingException:
Conflicting getter definitions for property "id": org.citi.facility.GetterMethodsObject#isId(0 params) vs org.citi.facility.GetterMethodsObject#getId(0 params)

As id is Integer so, I am expecting Jackson to call getId() method but not isId(). isId() method should be called only if id is boolean? Even I put @JsonIgnore it is not helping. I can not change actual object. How to fix this issue?

like image 675
user3435827 Avatar asked Mar 19 '14 03:03

user3435827


1 Answers

Jackson library checks getter/setters methods for serializing/deserializing. You can omit this annoying bug by below dirty hack. You have to use two annotations:

  1. @JsonIgnore - tell Jackson to ignore this property
  2. @JsonProperty("isId") - tell Jackson to use this method name in serialization process. It looks like Jackson found collision because it found two methods and these two methods link to one field - id.

Your POJO class should look like below:

class GetterMethodsObject {

    private int id = 10;

    public int getId() {
        return id;
    }

    @JsonIgnore
    @JsonProperty("isId")
    public boolean isId() {
        return true;
    }
}

Another solution: you should rename isId method because it is confusing. You should consider: hasId or even better hasValidId. I do not know what your's isId method is doing but you should give much more information in method name.

like image 78
Michał Ziober Avatar answered Sep 19 '22 16:09

Michał Ziober