我在第三方库中有一个标记为final的课程,我正在尝试使用Jackson将json反序列化为这个,但我得到了
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field
由于它是第三方而且最终我无法添加@JsonProperty
来定义新名称。
如何重新映射给定的属性名称以使用其他属性?
更新:mixins是要走的路,我做错了。
我正在尝试使用MixIns
这就是我正在做的事情:
package com.some.stuff;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
final class Closed implements Serializable {
private List<Other> others;
public List<Other> getOthersList() {
return others;
}
public void setOthersList( List<Other> others ) {
this.others = others;
}
}
final class Other implements Serializable {
private String data;
public void setData(String data) {
this.data = data;
}
public String getData() {
return this.data;
}
}
abstract class OthersMixIn {
OthersMixIn(@JsonProperty("others") List<Other> othersList){}
}
class Main {
public static void main( String ... args ) {
String json = "{\"others\":[{\"data\":\"d\"}]}";
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Closed.class, OthersMixIn.class);
mapper.getDeserializationConfig().addMixInAnnotations(Closed.class, OthersMixIn.class);
try {
Closed closed = mapper.readValue( json , Closed.class);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "others" (Class com.some.stuff.Closed), not marked as ignorable
at [Source: java.io.StringReader@28d47c65; line: 1, column: 12] (through reference chain: com.some.stuff.Closed["others"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
at org.codehaus.jackson.map.deser.std.StdDeserializer.reportUnknownProperty(StdDeserializer.java:673)
at org.codehaus.jackson.map.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:659)
at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:1365)
at org.codehaus.jackson.map.deser.BeanDeserializer._handleUnknown(BeanDeserializer.java:725)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:703)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at com.some.stuff.Main.main(Main.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)