[英]MessageBodyWriter not found for media type=application/xml
I want to make a REST API Response in two formats depending on the HttpHeaders of the request :我想根据请求的 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();
}}
It's working for the MediaType.APPLICATION_JSON, but for MediaType.APPLICATION_XML I get the following Error :它适用于 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.
Any Idea to solve this problem?任何想法来解决这个问题?
Do you have the jaxb dependency in your project?您的项目中是否有 jaxb 依赖项?
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>x.x.x</version>
</dependency>
If yes, perhaps you could try to wrap the exception.getErrors()
(which appears to be a Map?) into a GenericEntity
and giving that entity to the response:如果是,也许您可以尝试将
exception.getErrors()
(这似乎是一个 Map?)包装到一个GenericEntity
并将该实体提供给响应:
GenericEntity<Map<?, ?>> entity = new GenericEntity..
return Response.status(Status.X).entity(entity).type(MediaType.APPLICATION_XML).build();
Adding GenericEntity<>
, as described by ialex
, solved my problem.添加
GenericEntity<>
,如ialex
,解决了我的问题。 This is what I did:这就是我所做的:
GenericEntity<List<?>> genericEntity = new GenericEntity<List<?>> (exception.getErrors()) {};
Response.status(Status.BAD_REQUEST).entity(genericEntity).build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.