![](/img/trans.png)
[英]Is is possible to create a combo-annotation which combines multiple field annotations?
[英]Substitute complicated combo of annotations with one custom annotation
在我當前的項目中,我需要這組龐大而又復雜的注釋,我必須在課堂上放置很多字段。 它們是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 {
}
所以我的問題是:有可能嗎? 還是我做錯了什么?
更新 :我在此線程中找到了特殊傑克遜案例的答案創建自定義傑克遜注解
但我願意接受任何一般情況的解決方案。
使用默認的傑克遜庫,您將沒有運氣。
這是JacksonAnnotationIntrospector
的代碼片段(來自傑克遜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
。 Jackson不會像您想要的那樣在其他注釋上搜索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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.