Java - Jersey and Jackson for JSON serialization in streaming mode

less than 1 minute read

With Jersey and Jackson combination, we can build the streaming API for serializing very large size of data.

Please find the below pseudo code example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import javax.ws.rs.core.StreamingOutput;
import com.fasterxml.jackson.databind.ObjectMapper;


public class TestResource {

  private Iterator<Item> unknownLengthIterator;
  private ObjectMapper objectMapper;

  @GET
  @Produce(MediaType.APPLICATION_JSON)
  public Response getAllStream() {
    StreamingOutput streamingOutput = output -> {
      JsonFactory jsonFactory = objectMapper.getFactory();
      try (JsonGenerator jsonGenerator = jsonFactory.createGenerator(output)) {
        jsonGenerator.writeStartArray();
        unknownLengthIterator.forEach(item -> {
          try {
            jsonGenerator.writeObject(item);
          } catch (IOException e) {

          }
        });

        jsonGenerator.writeEndArray();
        jsonGenerator.flush();
      }
    }

    return Response.ok().entity(streamingOutput).build();
  }
}

Categories:

Updated: