英文:
How to solve conflicting getter definitions for property in jackson without access to source
问题
我遇到了这个错误:
HTTP状态500 - 无法编写JSON:属性"oid"存在冲突的getter定义
问题在于该类有两个类似的方法:
getOID(已弃用)和 getOid
但我无法修改这个类,因为它只是一个依赖项。
有办法解决这个问题吗?
英文:
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?
答案1
得分: 2
如果您无法修改POJO,您可以实现自定义序列化器或使用MixIn特性。
假设您的类如下所示:
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;
    }
}
您需要创建一个带有额外配置的接口:
interface IdIgnoreConflictMixIn {
    @JsonIgnore
    int getOID();
    @JsonProperty
    int getOid();
}
现在,您需要注册这个接口:
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);
    }
}
以上代码输出:
{"oid":1}
另请参阅:
- 特定类中特定类型的自定义Jackson序列化器
 - @JsonIgnore注解的等效代码设置是什么?
 - Jackson解析带有去除根元素但无法设置@JsonRootName的JSON
 - 使Jackson序列化器覆盖特定的被忽略字段
 
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论