Render Json strings from Elastic API client objects


I am using the Elasticsearch API client (8.9) for java and wondering how to render those Queries and Responses as json strings.
For example I can do a simple query like so:

val query = Query.of { q -> q.matchAll { it } }
val request = SearchRequest.of {
val response =,

val queryJson = query.toString() // this yields the json but there is "Query: " prepended
val responseJson = response.toString()  // this yields the json but there is "SearchResponse: " prepended

val mapper = ObjectMapper()
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
val string = mapper.writeValueAsString(result) // this works

Since the client can render the whole thing as json in the toString method the capability is there. There is just a type annotation prepended and I can't find a method to just render the whole thing as json.
Jackson ObjectMapper can render it if I configure it to render fields and not look for getters, but this seems to be unecessarily complicated the the objects themselven can render as json.
So my question is, what is the best way to get all these things as Json strings with an onboard method or do I really have to rely on an external Json mapper?

Cheers and thanks!

Have a look at this class:


There's a toJsonString() method.

Thanks again for the fast reply, it works like a charm. Yields the same results as objectMapper but I feel way more comfortable using an ES scoped class for this than a generic mapper!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.