Serialize Java 8 Stream with Jersey

后端 未结 2 915
無奈伤痛
無奈伤痛 2021-01-12 19:02

How can I serialize a Java 8 java.util.Stream with Jersey. I tried to write a MessageBodyWriter, but I need to know how to compose (decora

2条回答
  •  一向
    一向 (楼主)
    2021-01-12 19:36

    In line with the purpose of use streams (without using stream.collect(Collectors.toList())), there's this interesting article showing how to serialize large data from a database.

    It's something like this...

    @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();
    }
    

    It's not implemented with a MessageBodyWriter, but could adapted in my opinion.

提交回复
热议问题