簡體   English   中英

找不到 Media type=application/xml 的 MessageBodyWriter

[英]MessageBodyWriter not found for media type=application/xml

我想根據請求的 HttpHeaders 以兩種格式制作 REST API 響應:

@Context
HttpHeaders headers; 

public Response toResponse(MyValidationException exception) {
   if(headers.getMediaType().toString().equals(MediaType.APPLICATION_XML)){
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_XML).build();
  }else{
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_JSON).build();
}}

它適用於 MediaType.APPLICATION_JSON,但對於 MediaType.APPLICATION_XML,我收到以下錯誤:

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo MessageBodyWriter not found for media type=application/xml, type=class java.util.HashMap$EntrySet, genericType=class java.util.HashMap$EntrySet.

任何想法來解決這個問題?

您的項目中是否有 jaxb 依賴項?

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-jaxb</artifactId>
  <version>x.x.x</version>
</dependency>

如果是,也許您可​​以嘗試將exception.getErrors() (這似乎是一個 Map?)包裝到一個GenericEntity並將該實體提供給響應:

GenericEntity<Map<?, ?>> entity = new GenericEntity..

return Response.status(Status.X).entity(entity).type(MediaType.APPLICATION_XML).build();

添加GenericEntity<> ,如ialex ,解決了我的問題。 這就是我所做的:

GenericEntity<List<?>> genericEntity = new GenericEntity<List<?>> (exception.getErrors()) {};
Response.status(Status.BAD_REQUEST).entity(genericEntity).build();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM