Java – what is the best way to create an InputStream from Jackson jsonnode?
•
Java
I want to find the smartest way to create the Java library Jackson's jsonnode's InputStream
So far, I have done:
IoUtils.toInputStream(jsonNode.toString());
However, this method converts jsonnode to string before creating InputStream
unwanted:
org.apache.http.entity.InputStreamEntity entity = new InputStreamEntity(IoUtils.toInputStream(jsonNode.toString()));
Solution
>In most cases, if you use objectmapper to directly generate byte arrays, JSON will be written as UTF - 8 and some memory can be saved
ObjectMapper objectMapper = new ObjectMapper(); JsonNode json = ...; byte[] bytes = objectMapper.writeValueAsBytes(json);
Specifically, the Apache HTTP client provides bytearrayentity for byte arrays For other purposes, there is a bytearrayinputstream
Of course, objectmapper should only be created once and reused. > If you really want to write JSON as a stream, you can use a pair of pipedinputstream and pipedoutputstream, but as described in Javadoc
Example:
ObjectMapper objectMapper = new ObjectMapper(); JsonNode json = ...; PipedInputStream in = new PipedInputStream(); new Thread(() -> { try { IoUtils.copy(in,System.out); } catch (IOException e) { ... } }).start(); try ( PipedOutputStream out = new PipedOutputStream(in); JsonGenerator gen = objectMapper.getFactory().createGenerator(out); ) { gen.writeTree(json); } catch (IOException e) { ... }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码