0

I have a spring boot application. POST request of Router Function is getting List of Employee objects where date-of-birth in Employee class is expected to be in yyyy-MM-dd format while received json body is having date-of-birth in dd/MM/yyyy format.

As I don't want to change date format at global level, is there any way where I can de-serialize dd/MM/yyyy date-of-birth to yyyy-MM-dd coming via request body.

@JsonFormat(pattern = "yyyy-MM-dd") will not work as it expect date coming in request body should be in yyyy-MM-dd format while in my case date is coming in dd/MM/yyyy format.

EmployeeDto

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonNaming(SnakeCaseStrategy.class)
public class EmployeeDto {

    private String name;
    private String gender;
    private LocalDate dateOfBirth;
}

Router Config

@Bean
public RouterFunction<ServerResponse> employeeRoutes(EmployeeHandler employeeHandler) {
    return route(POST("/employees").and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)),
                    employeeHandler::saveEmployees);
}

EmployeeHandler

public class EmployeeHandler {

    private final EmployeeService employeeService;

    public Mono<ServerResponse> saveEmployees(ServerRequest serverRequest) {
        return ServerResponse.ok()
                .body(serverRequest.bodyToMono(new ParameterizedTypeReference<List<EmployeeDto>>() {})
                                .flatMap(EmployeeService::saveEmployees)
                                .doOnError(throwable -> log.error("Could not save employees", throwable)),
                        Map.class);
    }
}
user2800089
  • 2,015
  • 6
  • 26
  • 47
  • Can you provide more details and what your post method looks like? What's the data type of date of birth in the Employee class? – Tavo Sanchez Mar 25 '21 at 08:30
  • @TavoSanchez I have added more details – user2800089 Mar 25 '21 at 08:53
  • 1
    Ok, thanks. Have you tried this https://stackoverflow.com/questions/29956175/json-java-8-localdatetime-format-in-spring-boot ? Basically, you add a `jackson-datatype-jsr310` and use `@JsonDeserialize(using = LocalDateDeserializer.class)` on the dateOfBirth – Tavo Sanchez Mar 25 '21 at 10:06

0 Answers0