我有一个第三方类 SpecialObject 作为:
public class SpecialObject {
private String name;
private Integer id;
private Date date;
public String getFoo() {return "foo";} //Outlier
public String getName() { return name;}
public Integer getId() {return id;}
public Date getDate() {return date;}
public void setName(String name) {this.name = name;}
public void setId(Integer id) {this.id = id;}
public void setDate(Date date) {this.date = date;}
}
我希望在序列化它时只投影名称和日期属性。使用来自 Jackson 的 MixinAnnotation 的魔力,我创建了一个 Mixin 接口:
@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface SpecialObjectMixin {
@JsonProperty
public String getName();
@JsonProperty
public Date getDate();
}
为了便于将此 SpecialObject 作为参数处理,我还定义了一个实现 fromString() 方法的 SpecialObjectHandler。
@Override
public SpecialObject fromString(String json) {
try {
return objectMapper.readValue(json, SpecialObject.class);
} catch (IOException exception) {
throw new IllegalArgumentException("Unable to write JSON output",
exception);
}
}
当反序列化器调用这个方法时,objectMapper 会抛出一个错误
Caused by: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "foo" (Class com.kilo.SpecialObject), not marked as ignorable
at [Source: java.io.StringReader@2d2217da; line: 1, column: 60] (through reference chain: com.kilo.SpecialObject["foo"])
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.kilo.SpecialObjectHandler.fromString(SpecialObjectHandler.java:34)
我的问题是,有没有一种方法可以让 objectMapper (org.codehaus.jackson.map.ObjectMapper) 也尊重来自 Mixin 的注释,我将它配置为仅处理名称和日期?随意指出一些我可能忽略的基本内容。提前致谢!