我正在使用 Jersey 构建 REST 服务并希望返回 Collection<String>
作为 XML。
@GET
@Produces(MediaType.TEXT_XML)
@Path("/directgroups")
public Response getDirectGroupsForUser(@PathParam("userId") String userId) {
try {
Collection<String> result = service.getDirectGroupsForUser(userId, null, true);
// return result; //first try
// return result.toArray(new String[0]); //second try
return Response.ok().type(MediaType.TEXT_XML).entity(result).build(); //third try
} catch (UserServiceException e) {
LOGGER.error(e);
throw new RuntimeException(e.getMessage());
}
}
但我的尝试因以下异常而失败:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.ArrayList, and Java type class java.util.ArrayList, and MIME media type text/xml was not found
我通过谷歌发现的异常的所有结果都处理返回 text/json 而不是像我的情况那样的 text/xml。
谁能帮帮我?我想,如果我使用 Response,那将是我在 XML 中的根元素,而我的集合是其中的字符串元素列表。
最佳答案
使用
List<String> list = new ArrayList<String>();
GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) {};
Response response = Response.ok(entity).build();
通用实体包装器用于在使用响应构建器时获取输出。
关于java - 未找到 Java 类 java.util.ArrayList... 和 MIME 媒体类型文本/xml 的消息正文编写器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15618061/