我想根据请求的 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();