找不到媒体类型= application / xml的MessageBodyWriter

时间:2017-11-16 10:24:40

标签: java spring rest web-services jersey

我希望以两种格式制作REST API响应,具体取决于请求的HttpHeader:

@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.

有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您的项目中是否有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();

答案 1 :(得分:1)

GenericEntity<>所述,添加ialex解决了我的问题。这就是我所做的:

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