Java 如何将自定义MessageBodyWriter应用于对象列表?
在Dropwizard web服务中,我希望使用以下自定义Java 如何将自定义MessageBodyWriter应用于对象列表?,java,jersey,dropwizard,Java,Jersey,Dropwizard,在Dropwizard web服务中,我希望使用以下自定义MessageBodyWriter返回数据库中类Test的对象 @Provider @Produces("application/Test") public class TestMarshaller implements MessageBodyWriter<Test>{ public long getSize(Test obj, Class<?> type, Type genericType, An
MessageBodyWriter
返回数据库中类Test
的对象
@Provider
@Produces("application/Test")
public class TestMarshaller implements MessageBodyWriter<Test>{
public long getSize(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type == Test.class;
}
public void writeTo(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException, WebApplicationException {
httpHeaders.add("Content-Type", "text/plain; charset=UTF-8");
StringBuffer str = new StringBuffer();
str.append(obj.getData());
outputStream.write(str.toString().getBytes());
}
}
现在我想对元素列表使用相同的MessageBodyWriter
@GET
@Produces("application/Test")
@Path("/{ID}")
public List<Test> getTest(@PathParam(value = "ID") String IDs) {
List<Test> listTest = Test.findMultiInDB(IDs);
return listTest;
}
不幸的是,它导致了与上述完全相同的错误。我的问题是,我需要更改什么才能使其正常工作,还是需要另一个
MessageBodyWriter
来处理列表?错误消息很清楚,Jersey查找类型为java.util.List
的MessageBodyWriter
,但只找到MessageBodyWriter
,所以,要么为ListMessageBodyWriter
创建一个新的,要么使用Object
并在Object类上使用if-else 错误消息很清楚,Jersey查找类型为java.util.List
的MessageBodyWriter
,但只找到MessageBodyWriter
,因此可以为ListMessageBodyWriter
创建一个新的,或者使用对象
并在对象类上使用if-else 您是否可以尝试使用Object
作为MessageBodyWriter
的类型参数而不是Test
您是否可以尝试使用Object
作为MessageBodyWriter
的类型参数而不是Test
为列表使用writer似乎是更明智的方法。谢谢。为列表使用编写器似乎是更明智的方法。非常感谢。
@GET
@Produces("application/Test")
@Path("/{ID}")
public List<Test> getTest(@PathParam(value = "ID") String IDs) {
List<Test> listTest = Test.findMultiInDB(IDs);
return listTest;
}
@GET
@Produces("application/Test")
@Path("/{ID}")
public Response getTest(@PathParam(value = "ID") String IDs) {
List<Test> listTest = Test.findMultiInDB(IDs);
GenericEntity<List<Test>> result = new GenericEntity<List<Test>>(listTest) {};
return Response.ok(result).build();
}