如何使用Jersey序列化Java 8 java.util.Stream<T>
。我尝试编写MessageBodyWriter
,但我需要知道如何使用MessageBodyWriters
的新MessageBodyWriter
为现有Stream
撰写(装饰)。
Stream<String> get(){
return some stream of strings
}
public <T> class StreamMessageBodyWriter<Stream<T>>
implements MessageBodyWriter<Stream<T>> {
public void writeTo(.......){
//How can I get the handle to MessageBodyWriter that will write for type T,
//so that I can 'collect' the 'java.util.Stream<T>' and write it to
//OutputStream
}
}
答案 0 :(得分:4)
但是我需要知道如何使用
MessageBodyWriters
的新MessageBodyWriter
撰写(装饰)现有Stream
您可以注入Providers
并使用getMessagBodyWriter(...)
,传递所需的详细信息以查找该类型的特定编写者。例如
@Provider
public class StreamBodyWriter implements MessageBodyWriter<Stream> {
@Context
private Providers providers;
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Stream.class.isAssignableFrom(type);
}
@Override
public long getSize(Stream stream, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) { return -1; }
@Override
public void writeTo(Stream stream, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
Object obj = stream.collect(Collectors.toList());
Class<?> objType = obj.getClass();
MessageBodyWriter writer = providers.getMessageBodyWriter(objType,
null, annotations, mediaType);
writer.writeTo(obj, objType, null, annotations,
mediaType, httpHeaders, entityStream);
}
}
如果查看writeTo
,请先致电collect
,然后获取返回的类型。然后查找该类型的编写器,然后简单地委托给编写者。
这是一个测试
@Path("stream")
public class StreamResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getStream() {
List<Person> myList = Arrays.asList(
new Person("Stack"),
new Person("Overflow"),
new Person("Sam"));
Stream<Person> stream = myList.stream()
.filter(p -> p.name.startsWith("S"));
return Response.ok(stream).build();
}
public static class Person {
public String name;
public Person(String name) { this.name = name; }
public Person() {}
}
}
C:\>curl -v http://localhost:8080/api/stream
的结果:强>
[{"name":"Stack"},{"name":"Sam"}]
顺便说一句,如果您打算在编写器中操作Stream,可以考虑使用Interceptor。真的不会有所作为,但是如果你想坚持单一责任原则,这就是Interceptor
的用途,操纵请求体。
注意:以上是标准的JAX-RS
特别是对于Jersey,您还可以注入MessageBodyWorkers
,以进行更具体的查找,甚至可以调用writeTo
,如果有的话,将会委托给所需的编写者。
答案 1 :(得分:0)
根据使用流的目的(不使用stream.collect(Collectors.toList())
),这篇有趣的文章显示how to serialize large data from a database。
它是这样的......
@GET
@Produces( "application/json" )
public Response streamGeneratedUuids() {
return getNoCacheResponseBuilder( Response.Status.OK ).entity( new StreamingOutput() {
@Override
public void write( OutputStream os ) throws IOException, WebApplicationException {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))) ) {
//iterate the java.util.stream and write to the OutputStream
writer.print("....");
}
}
}).build();
}
它没有用MessageBodyWriter实现,但在我看来可以改编。