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

2024-01-10

我想根据请求的 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()(这似乎是一张地图?)GenericEntity并将该实体提供给响应:

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

return Response.status(Status.X).entity(entity).type(MediaType.APPLICATION_XML).build();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

找不到媒体类型 = application/xml 的 MessageBodyWriter 的相关文章

随机推荐