2016-08-12 36 views
3

我重寫MessageBodyWriterWriteTo方法:如何在澤西的MessageBodyWriter的writeTo方法中獲取anotations值?

@Override 
public void writeTo(Detail detail, Class<?> type, Type genericType, Annotation[] annotation, MediaType mediaType, 
     MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { 
} 

有一個annotation參數。其實我想從中取view註釋,以便我可以根據view返回Detail數據。

這裏是我的WriteTo代碼:

ObjectMapper mapper = new ObjectMapper(); 
mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false); 
mapper.writerWithView(JSONView.CustomerView.class).writeValue(entityStream, detail); 

其實,我想從註釋獲取視圖名稱,這樣我就可以根據視圖返回的具體數據。

如何從anotation中獲取view類名?

這裏是我的資源代碼:

@POST 
@Produces({MediaType.APPLICATION_JSON}) 
@Path("testDetail") 
@JsonView(JSONView.TicketView.class) 
public TestDetail testDetail() 
{ 
    TestDetail testDetail = new TestDetail(); 
    return testDetail; 
} 

回答

-1

你可以這樣做:

JsonView jsonView = this.getClass().getAnnotation(JsonView.class); 

JsonView jsonView = TestDetail.class.getAnnotation(JsonView.class); 

的方法使用:

Method method = this.getClass().getMethod("testDetail"); (or this.getClass().getDeclaredMethod("testDetail")) 
JsonView type = method.getAnnotation(JsonView.class); 

,只是後做:

type.value() 
+0

它不工作,任何其他解決方案? – unknownbits

+0

對不起,你想要的方法,我會更新代碼。 – Deceiver

+0

在哪個包中的方法是?? – unknownbits

0

我知道你是在獲得資源的方法的註釋,你自定義實現MessageBodyWriter特別感興趣。但是你不需要爲你在問題中提到的目的做這件事。

JAX-RS的傑克遜模塊開箱即用地提供了此功能,您不需要自己編寫它。引用project page

除了註釋值類之外,還可以將Jackson註釋的子集與提供者一起使用。 下面是與所有格式的支持工作註釋的簡短列表:

  • @JsonView可以用來定義活動視圖的特定端點

[...]

jersey-media-json-jackson工件對jackson-jaxrs-json-provider工件有依賴性,可爲您提供此功能。因此,只需將Jackson配置爲您的JSON提供商(有關更多詳細信息,請參閱此answer),並支持@JsonView即開即用。

+0

你好,我想這樣做。我有要求。 :-)請建議一些事情 – unknownbits