我想根据请求的 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();
关于java - 找不到 Media type=application/xml 的 MessageBodyWriter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47327162/