Skip to content

[QUESTION] toJsonString() with Java 8 time module #1730

@j0r0

Description

@j0r0

Hi,
I don't seem to be able to serialise SearchRequest(for example) if i am using OffsetDateTime in my range query.
For example:

OffsetDateTime from, OffsetDateTime to;
BoolQuery.Builder bool = QueryBuilders.bool();
bool.filter(QueryBuilders.range().field("ts").from(JsonData.of(from)).to(JsonData.of(to)).build().toQuery());

SearchRequest searchRequest = new SearchRequest.Builder()
				.size(10000)
				.query(bool.build().toQuery())
				.index(Arrays.stream(indices).toList()).build();

		System.out.println(searchRequest.toJsonString());// This is where the error is

The error is

jakarta.json.JsonException: Cannot find a serializer for type java.time.OffsetDateTime. Consider using a full-featured JsonpMapper.

This is how i init my Opensearch client and setting the mapper which has the timeModule

private OpenSearchClient getClientInternal() {
        final HttpHost host = new HttpHost("https",hostname);
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(username, password.toCharArray()));
        
        JsonpMapper mapper = new JacksonJsonpMapper(jacksonObjectMapper);

        var transport = ApacheHttpClient5TransportBuilder.builder(host)
                .setMapper(mapper) //**Set the mapper here which has the timeModule**
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
        )
        .build();

        return new OpenSearchClient(transport);
    }

My ObjectMapper config

@Bean
    public ObjectMapper jacksonObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        System.out.println("Auto-configured Jackson ObjectMapper bean created. "+ mapper.hashCode());
        return mapper;
    }

I don't see anything wrong, but i still get the error.

Any ideas ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions