简体   繁体   中英

Jackson JSON to stream parser

I would like to process response from HttpRequest (JSON object) as stream. That's mean filter only data field which interest me and return it as a stream and process it further (send as HttpServletResponse). I don't want to load it to memory as the response.body() might be huge (1 000 000+ lines). Unfortunately I don't see any method on JsonParser class that would return stream.

HttpResponse<InputStream> response = client.send(httpRequest, BodyHandlers.ofInputStream());
InputStream result = response.body();
JsonFactory factory = new JsonFactory();
try(JsonParser parser = factory.createParser(result)){
  while (parser.nextToken() != JsonToken.END_OBJECT) {
    if ("data".equals(parser.getCurrentName())) {
      parser.getValueAsString(); // it returns correct lines but as String
    }
  }
}

Does anybody know how to handle it? Or maybe I should use some other library/API?

You already process the input data as a stream, so it can easily be written to another stream like an HttpServletResponse .

Get the outputstream you want to transfer the data to:

ServletOutputStream out = httpServletResponse.getOutputStream();

And for each data string, write the value to the new stream:

while ... {
    if ("data".equals(parser.getCurrentName())) {
        String data = parser.getValueAsString();
        out.write(data.getBytes("UTF-8"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM