javaspring-bootserializationencodingspring-cloud-feign

How to serialise Date of request body in a specific format in Feign Client?


I try to send a request to a third party api using feign client. When I check the request body, it looks like below:

{
  "requestTime": "2023-06-07T12:18:00.916+00:00"
}

but the api only accept the date format yyyy-MM-dd'T'mm:HH:ss.SSSZ, so the valid request body would be something similar below:

{
  "requestTime": "2023-06-17T14:53:47.402Z"
}

How do I config the serialisation of date format in Feign Client?

My codes:

@FeignClient(value = "myfeign", url = "https://myfeign.com/")
public interface MyFeignClient {

    @PostMapping(value = "/myfeign/", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
    MyResponse sendRequest(MyRequest request);
}

And MyRequest is generated from openapi-generator.

public class MyRequest {
   @JsonProperty("requestTime")
   @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
   private Date requestTime;
   // getter...
}

Edit: My approach below doesn't work as the request object still use "2023-06-07T12:18:00.916+00:00" format.

public class MyFeignConfig {

    @Bean
    public Encoder feignEncoder() {
        HttpMessageConverter<Object> jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper());

        HttpMessageConverters httpMessageConverters = new HttpMessageConverters(jacksonConverter);
        ObjectFactory<HttpMessageConverters> objectFactory = () -> httpMessageConverters;


        return new SpringEncoder(objectFactory);
    }

    private ObjectMapper objectMapper() {
        final String DATE_FORMAT = "yyyy-MM-dd'T'mm:HH:ss.SSSZ";
        SimpleDateFormat dateFormat = new SimpleDateFormat((DATE_FORMAT));
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(dateFormat);
    }

add configuration in the client

@FeignClient(value = "myfeign", url = "https://myfeign.com/",  configuration = "MyFeignConfig.class")
public interface MyFeignClient {

    @PostMapping(value = "/myfeign/", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
    MyResponse sendRequest(MyRequest request);
}

Solution

  • You need to use single quote for Z in the format string like below

    final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";