简体   繁体   中英

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();

Disable the ACCEPT_EMPTY_STRING_AS_NULL_OBJECT on your mapper with:

objectMapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

ACCEPT_EMPTY_STRING_AS_NULL_OBJECT: Feature that can be enabled to allow JSON empty String value ("") to be bound to POJOs as null.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM