如何在无法访问源代码的情况下解决Jackson中属性的冲突getter定义。

huangapple go评论160阅读模式
英文:

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}

另请参阅:

英文:

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:

huangapple
  • 本文由 发表于 2020年8月19日 03:14:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63475238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定