Writing byte[] as text to JsonGenerator

7 views
Skip to first unread message

Volkan Yazıcı

unread,
Oct 1, 2019, 8:10:03 AM10/1/19
to jackson-user
Hello,

I have a byte[] of a text. How can I write (incl. escaping) this to a JsonGenerator. JsonGenerator#writeRawUTF8String(byte[] buffer, int offset, int length) does the job, but misses escaping.

To provide further background, I am trying to serialize a stack trace to text. But while doing so, I am using a pool of byte[] to avoid allocation. That is,

public void resolve(Throwable throwable, JsonGenerator jsonGenerator) throws Exception {
ByteBufferOutputStream outputStream = outputStreamPool.acquire();
try (PrintStream printStream = new PrintStream(outputStream, false, "UTF-8")) {
exception.printStackTrace(printStream);
}
ByteBuffer outputStreamBuffer = outputStream.getByteBuffer();
jsonGenerator.writeRawUTF8String(outputStreamBuffer.array(), 0, outputStreamBuffer.position());
outputStreamPool.release(outputStream);
}

I will appreciate any tips.
Thanks in advance.

Best.

Tatu Saloranta

unread,
Oct 1, 2019, 1:53:19 PM10/1/19
to jackson-user
On Tue, Oct 1, 2019 at 5:10 AM Volkan Yazıcı <volkan...@gmail.com> wrote:
>
> Hello,
>
> I have a byte[] of a text. How can I write (incl. escaping) this to a JsonGenerator. JsonGenerator#writeRawUTF8String(byte[] buffer, int offset, int length) does the job, but misses escaping.

If you need escaping, you will not really benefit from feeding UTF-8
encoded input source: it will unfortunately need to go back to
character, that is, decoded into Java Strings or `char[]`.

-+ Tatu +-
Reply all
Reply to author
Forward
0 new messages