Truncate long texts using JsonGenerator

278 views
Skip to first unread message

Volkan Yazıcı

unread,
May 27, 2019, 3:35:28 PM5/27/19
to jackson-user
Hello,

log4j2-logstash-layout uses Jackson JsonGenerator to emit JSON. There is a ticket on the project asking for truncating strings longer than a certain value. The most straightforward (and crude?) approach, I guess, would be to wrap every JsonGenerator#writeFieldName, JsonGenerator#writeString, etc. with a condition on the input. Is there any other way to have the same effect?

Best.

Tatu Saloranta

unread,
May 28, 2019, 1:39:35 AM5/28/19
to jackson-user
On Mon, May 27, 2019 at 12:35 PM Volkan Yazıcı <volkan...@gmail.com> wrote:
>
> Hello,
>
> log4j2-logstash-layout uses Jackson JsonGenerator to emit JSON. There is a ticket on the project asking for truncating strings longer than a certain value. The most straightforward (and crude?) approach, I guess, would be to wrap every JsonGenerator#writeFieldName, JsonGenerator#writeString, etc. with a condition on the input. Is there any other way to have the same effect?

That is a reasonable and highly efficient approach. Something that can
make that approach much easier is

com.fasterxml.jackson.core.util.JsonGeneratorDelegate

which allows you to create such a wrapper: you just override methods
you want, others are delegated by default.

Alternatively if databind (ObjectMapper or ObjectWriter) is used, you
could consider custom String serializer which might also work. That
would not cover field names but perhaps those are not the primary
problems. Similarly datatypes other than `String` are handled using
different serializers so applicability of this approach depends on
details.

Oh and now that I think, you could also possibly first "serializer"
input into `Map`:

Map<String, Object> stuff = mapper.convertValue(logEntry, Map.class);

then traverse entries, truncating if need be, and then serialize that Map.

Actually this would probably be my suggestion.

I hope this helps,

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