繁体   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