我有一个第三方库类(来自 Apache Axis),我想通过 Jackson JSON 序列化它:
public class NonNegativeInteger extends BigInteger {
public NonNegativeInteger(byte[] val) {
super(val);
checkValidity();
} // ctor
public NonNegativeInteger(int signum, byte[] magnitude) {
super(signum, magnitude);
checkValidity();
} // ctor
public NonNegativeInteger(int bitLength, int certainty, Random rnd) {
super(bitLength, certainty, rnd);
checkValidity();
} // ctor
public NonNegativeInteger(int numBits, Random rnd) {
super(numBits, rnd);
checkValidity();
} // ctor
public NonNegativeInteger(String val) {
super(val);
checkValidity();
}
public NonNegativeInteger(String val, int radix) {
super(val, radix);
checkValidity();
} // ctor
/**
* validate the value against the xsd definition
*/
private BigInteger zero = new BigInteger("0");
private void checkValidity() {
if (compareTo(zero) < 0) {
throw new NumberFormatException(
Messages.getMessage("badNonNegInt00")
+ ": " + this);
}
} // checkValidity
/**
* Work-around for http://developer.java.sun.com/developer/bugParade/bugs/4378370.html
* @return BigIntegerRep
* @throws ObjectStreamException
*/
public Object writeReplace() throws ObjectStreamException {
return new BigIntegerRep(toByteArray());
}
protected static class BigIntegerRep implements java.io.Serializable {
private byte[] array;
protected BigIntegerRep(byte[] array) {
this.array = array;
}
protected Object readResolve() throws java.io.ObjectStreamException {
return new NonNegativeInteger(array);
}
}
}
我的实体类包含NonNegativeInteger
我想通过 JSON 序列化的字段:
public class TestEntity {
private NonNegativeInteger number;
public NonNegativeInteger getNumber() {
return number;
}
public void setNumber(NonNegativeInteger number) {
this.number = number;
}
}
当我通过 Jackson JSON 序列化上述对象时,出现以下错误:
Can not instantiate value of type [simple type, class org.apache.axis.types.NonNegativeInteger] from Integral number; no single-int-arg constructor/factory method
然后我看了一下POST请求实体,其实是{"number" : 10}
正如杰克逊所连载的。但是由于NonNegativeInteger
没有采用单整型的构造函数,Jackson 无法实例化NonNegativeInteger
目的。所以我按照某人的建议添加了 Mixin 类NonNegativeInteger
这样它将有一个以 int 作为参数的构造函数:
public abstract class NonNegativeIntegerMixin extends NonNegativeInteger {
@JsonCreator
public NonNegativeIntegerMixin(int val) {
super(String.valueOf(val));
}
}
然后我将它注册到我的 JSON 配置类中:
objectMapper.addMixInAnnotations(NonNegativeInteger.class, NonNegativeIntegerMixin.class);
但并没有什么帮助,仍然报同样的错误。我尝试手动将 JSON 请求正文编写为{"number": "10"}
然后效果很好。但我的客户端使用 Jackson 来序列化NonNegativeInteger
。杰克逊自动转换为{"number": 10}
不带引号。我该如何修复这个错误?
Edit:
The NonNegativeInteger
类没有任何类字段(除了常量zero
场地)。这number
钥匙来自我的TestEntity
班级。所以我即使添加@JsonProperty
我的注释中NonNegativeIntegerMixin
mixin 类,Jackson JSON 不会实例化NonNegativeInteger
带有 int 类型 arg。因此,我仍然遇到同样的错误。