Не работает контроллер java
Нужно написать контроллер, который принимает json формата
[{"dateOfBirth":"2011-05-11"},{"dateOfBirth":"2021-02-01"}]
высчитывает количество человек и их возраст и возвращает определенную сумму Перепробовал все. Ошибка 400 или 500. Помогите плиз. Вот контроллер:
@RestController
@RequestMapping("/insurance/*")
public class InsuranceController {
private static final Logger logger = LoggerFactory.getLogger(InsuranceController.class);
@Autowired
private InsuranceService insuranceService;
@Autowired
private InsuredDTO insuredDTO;
@PostMapping(value = "/tickCalculate", consumes = "application/json")
@CheckSession
@CatchExceptionReport
public ResponseEntity<?> tickCalculate(@RequestBody ArrayList<InsuredDTO> insuredDTO)
{
try {
int resultCalculate = insuranceService.getCalculation(insuredDTO);
return new ResponseEntity<Object>(resultCalculate, HttpStatus.OK);
} catch (Exception e) {
logger.error("Something wrong: ", e);
return new ResponseEntity<Object>(new StatusResponse(Constants.ERROR, e.getMessage()), HttpStatus.BAD_REQUEST);
}
}
}
ДТО:
@Data
@Component
public class InsuredDTO {
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
public LocalDate dateOfBirth;
public int getAge() {return Period.between(this.dateOfBirth, LocalDate.now()).getYears();}
}
Сервис:
@Service
public class InsuranceService {
@Autowired
InsuredDTO insuredDTO;
public int getCalculation(ArrayList<InsuredDTO> ages) {
return ages.stream()
.mapToInt(InsuredDTO::getAge)
.map(age -> age < 18 ? 360 : 320)
.sum();
}
}
логи:
thread=sse-nio-8443-exec-94 class_path=.controllers.ControllerValidationHandler phone= sessionID= message="org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Text '2011-05-11' could not be parsed at index 2; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Text '2011-05-11' could not be parsed at index 2 (through reference chain: java.util.ArrayList[0]->ru.nskes.pserver.dtos.insurance.InsuredDTO[\"dateOfBirth\"])
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Text '2011-05-11' could not be parsed at index 2; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Text '2011-05-11' could not be parsed at index 2 (through reference chain: java.util.ArrayList[0]->ru.nskes.pserver.dtos.insurance.InsuredDTO[\"dateOfBirth\"])
Ответы (1 шт):
Автор решения: Анатолий
→ Ссылка
Проблема решена. Верный формат запроса [{"dateOfBirth":"11.05.2021"},{"dateOfBirth":"01.02.2021"}]