Lucas
Lucas

Reputation: 738

How to solve conflicting getter definitions for property in jackson without access to source

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?

Upvotes: 1

Views: 3113

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

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:

Upvotes: 2

Related Questions