我想找到一种从Java库的 JsonNode 创建 InputStream 的最聪明的方法杰克逊。
I would like to find the most clever way to create an InputStream from a JsonNode, of the Java library Jackson.
到目前为止我已经完成了:
Until now I have done:
IOUtils.toInputStream(jsonNode.toString());但这种方式将 JsonNode 转换为在创建 InputStream 之前 String 。
But this way converts the JsonNode into a String before creating the InputStream.
ex ex need :
ex of need:
org.apache.http.entity.InputStreamEntity entity = new InputStreamEntity(IOUtils.toInputStream(jsonNode.toString()));推荐答案
In大多数情况下JSON编写为UTF-8,如果使用ObjectMapper直接生成字节数组,则可以节省一些内存。
In most cases JSON is written as UTF-8 and you can save some memory, if you directly generate byte array using ObjectMapper. ObjectMapper objectMapper = new ObjectMapper(); JsonNode json = ...; byte[] bytes = objectMapper.writeValueAsBytes(json);
具体来说,Apache HTTP客户端提供ByteArrayEntity以用于字节数组。对于其他用途,有一个ByteArrayInputStream。
Specifically, Apache HTTP client provides ByteArrayEntity for use with byte array. For other uses, there is a ByteArrayInputStream.
当然,ObjectMapper应该只创建一次并重复使用。
Of course, ObjectMapper should be created only once and reused.
如果你真的想要以流方式编写JSON,可以使用一对PipedInputStream和PipedOutputStream,但是,因为JavaDoc状态
If you really want JSON to be written in a streaming manner, it is possible to use a pair of PipedInputStream and PipedOutputStream, however, as JavaDoc states
通常,一个线程从 PipedInputStream 对象读取数据,并将数据写入相应的 PipedOutputStream 由其他一些线程。不建议尝试使用单个线程中的两个对象,因为它可能使线程死锁。
Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.
示例:
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) { ... }
更多推荐
从Jackson JsonNode创建InputStream的最佳方法是什么?
发布评论