在我目前的项目中,我有一组庞大而复杂的注释,我必须在课堂上放置很多字段。他们是Jackson json注释。
@JsonSerialize(using = IViewableToReferenceSerializer.class, contentUsing = IViewableToReferenceSerializer.class)
private ComplexeObject myObject;
我想用它代替:
@JsonAsReference
private ComplexeObject myObject;
我已经在没有自定义注释的情况下测试了系统,它运行正常。我虽然可以将我的注释定义为(例如):
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JsonSerialize(using = IViewableToReferenceSerializer.class, contentUsing = IViewableToReferenceSerializer.class)
public @interface JsonAsReference {
}
所以我的问题是:它有可能吗?或者我只是做错了什么?
更新:我在这个主题中找到了杰克逊案件的答案 Create a custom Jackson annotation
但我对任何一般案例解决方案持开放态度。
答案 0 :(得分:1)
使用默认的jackson库,你将没有运气。
这是JacksonAnnotationIntrospector
(来自jackson 1.9.13)
public Object findSerializer(Annotated a)
{
/* 21-May-2009, tatu: Slight change; primary annotation is now
* @JsonSerialize; @JsonUseSerializer is deprecated
*/
JsonSerialize ann = a.getAnnotation(JsonSerialize.class);
if (ann != null) {
Class<? extends JsonSerializer<?>> serClass = ann.using();
if (serClass != JsonSerializer.None.class) {
return serClass;
}
}
....
}
正如您所看到的,只会考虑注释JsonSerialize
。杰克逊不会像你想要的那样在其他注释上搜索JsonSerialize
注释。
您可以实施自己的AnnotationIntrospector 并将其提供给SerializationConfig
和DeserializationConfig
,例如
AnnotationIntrospector annIntr = ....; // your implementation
ClassIntrospector<? extends BeanDescription> intr = new BasicClassIntrospector();
VisibilityChecker<?> vc = VisibilityChecker.Std.defaultInstance();
TypeFactory typeFactory= TypeFactory.defaultInstance();
SerializationConfig serConfig = new SerializationConfig(intr, annIntr, vc, null,
null, typeFactory, null);
DeserializationConfig deserConfig = new DeserializationConfig(intr, annIntr, vc, null,
null, typeFactory, null);
// null means use a default implementation
ObjectMapper objectMapper = new ObjectMapper(null, null, null, serConfig, deserConfig);