从Jackson JsonNode创建InputStream的最佳方法是什么? [英] What's the best way to create an InputStream from a Jackson JsonNode?

查看:260
本文介绍了从Jackson JsonNode创建InputStream的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种从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()));


推荐答案


  1. In大多数情况下JSON编写为UTF-8,如果使用ObjectMapper直接生成字节数组,则可以节省一些内存。

  1. 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的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆