7

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?

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
user3435827
  • 111
  • 1
  • 1
  • 3

1 Answers1

3

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.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146