1

I'm getting this error:

HTTP Status 500 - Could not write JSON: Conflicting getter definitions for property "oid"

The problem is that the class has two similar methods:

getOID (deprecated) and getOid

But I cannot modify the class as it's just a dependency.

Is there a way to fix this issue?

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
Lucas
  • 668
  • 1
  • 5
  • 17

1 Answers1

2

If you can not modify POJO you can implement custom serialiser or use MixIn feature.

Assume, your class looks like below:

class Id {
    private int oid;

    @Deprecated
    public int getOID() {
        return oid;
    }

    public int getOid() {
        return oid;
    }

    public void setOid(int oid) {
        this.oid = oid;
    }

    @Override
    public String toString() {
        return "oid=" + oid;
    }
}

You need to create an interface with extra configuration:

interface IdIgnoreConflictMixIn {
    @JsonIgnore
    int getOID();

    @JsonProperty
    int getOid();
}

Now, you need to register this interface:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonMixInApp {
    public static void main(String[] args) throws IOException {
        Id id = new Id();
        id.setOid(1);

        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(Id.class, IdIgnoreConflictMixIn.class);

        mapper.writeValue(System.out, id);
    }
}

Above code prints:

{"oid":1}

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • I have a Set people which I return in Spring using ResponseEntity.ok(people). How can I use the ObjectMapper in this situation? – Lucas Aug 18 '20 at 19:59
  • @Myntekt, in case of `Spring` you need to create new bean or customise already existed. Some examples how to do that you can find here: [Register a custom Jackson ObjectMapper using Spring Javaconfig](http://www.jworks.nl/2013/08/21/register-a-custom-jackson-objectmapper-using-spring-javaconfig/), [How to customise the Jackson JSON mapper in Spring Web MVC](https://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom/), [Configuring ObjectMapper in Spring](https://stackoverflow.com/questions/7854030/configuring-objectmapper-in-spring) – Michał Ziober Aug 18 '20 at 21:03