Search code examples
javaspringspring-bootmicroservicesresttemplate

Spring RestTemplate sends empty string as null?


I'm co-developing a piece of code that fetches some data via POST from an external microservice using JSON format both ways. The issue is that I'm sending an empty String, but the microservice comes back to me with an error message suggesting the fields I send are null whenever I send an empty String. Adding a space character eliminates the issue. Is there any chance that somehow the serialization is going wrong?

Thank you in advance.

This is my rest template:

final HttpEntity<?> httpRequestEntity = new HttpEntity<>(employeeRequest, copyAndAdjustHeaders(httpHeaders));
            final ResponseEntity<EmployeeResponseDto> exchange = restTemplate.exchange(employeeResourcePath, HttpMethod.POST, httpRequestEntity, EmployeeResponseDto.class);
            final EmployeeResponseDto body = exchange.getBody();

My object mapper configuration:

    @Bean
    public ObjectMapper objectMapper() {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        objectMapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
        objectMapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
        return objectMapper;
    }

And how i initialize the autowired RestTemplate in the constructor.

        this.restTemplate = restTemplateBuilder
                .setConnectTimeout(requestConnectionTimeoutMillis)
                .setReadTimeout(requestReadTimeoutMillis)
                .rootUri(employeeRootUri)
                .build();

Solution

  • The solution that solved it was to annotate the fields with @NotNull and @JsonInclude(JsonInclude.Include.NON_NULL) in the microservice that did the posting. It was still weird though it didn't replicate every single time across different environments. Now it works fine.