Wpis z mikrobloga

Hej mirki, nie mogę co źle robię w #springboot #java.

mam ja sobie klasę

@Data
@NoArgsConstructor
public class RegisterDateTimeRequest{
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING)
private LocalDateTime dateTime;


}


i mam sobie controller z metodą

@GetMapping
public RegisterDeviceDateTimeResponse performDeviceDateTime(
RegisterDateTimeRequest registerDeviceDateTimeRequest ){
// ...
}
podczas użycia http://localhost:8080/register?dateTime=2020-10-10T16%3A51%3A02
mam błąd 400 a w konsoli

Field error in object 'registerDeviceDateTimeRequest' on field 'dateTime': rejected value [2020-10-10T16:51:02];
codes [typeMismatch.registerDeviceDateTimeRequest.dateTime,typeMismatch.dateTime,typeMismatch.java.time.LocalDateTime,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [registerDeviceDateTimeRequest.dateTime,dateTime];
arguments []; default message [dateTime]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'dateTime';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type
[@org.springframework.format.annotation.DateTimeFormat @com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDateTime]
for value '2020-10-10T16:51:02';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-10-10T16:51:02]]]

o co kaman?!
  • 4
@JacobTheLiar: jako pierwszego podejrzanego sprawdziłbym pattern w DateTimeFormat, "yyyy-MM-dd HH:mm:ss" =/= "yyyy-MM-ddTHH:mm:ss"
Ewentualnie poleciłbym sprawdzić przekazywanie wartości do pola "iso" w tejże adnotacji, masz kilka standardowych formatów, a może któryś okaże się idealny w twojej sytuacji
@Bairei: @koozkie: ogólnie w patternie stosuję w większości spację i nie przeszkadzało to przyjęciu daty z T, tak sugeruje swagger którym to testuje. Ale uwaga cenna.

@Bairei: @imarid: racja wyszło na to, że to musi być iso w adnotacji od DateTimeFormat, przerobienie klasy z adnotacją @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) przyjmuje wartość nawet z dokładnością co do minuty. Bardziej jest to wyjaśnione w poście poniżej zaakceptowanego, który przysłał @imarid.