从Jackson JsonNode创建InputStream的最佳方法是什么?

编程入门 行业动态 更新时间:2024-10-24 18:21:06
本文介绍了从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()));

推荐答案

  • 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的最佳方法是什么?

    本文发布于:2023-07-17 06:46:54,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1130531.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:方法   Jackson   JsonNode   InputStream

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!