简体   繁体   中英

Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime

There are many similar questions for my problem but I didn't find resolution. Fragment of entity:

@DateTimeFormat
private LocalDateTime valid_from;

@DateTimeFormat
private LocalDateTime valid_to;

My form has format yyyy-MM-dd. I already tried annotation @DateTimeFormat(format="yyyy-MM-dd") and ISO. I tried with:

 @InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(true);
    webDataBinder.registerCustomEditor(LocalDateTime.class, new CustomDateEditor(dateFormat, true));
}

And:

@Converter(autoApply = false)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, String> {

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

@Override
public String convertToDatabaseColumn(LocalDateTime locDate) {
    return (locDate == null ? null : formatter.format(locDate));
}

@Override
public LocalDateTime convertToEntityAttribute(String dateValue) {
    return (dateValue == null ? null : LocalDateTime.parse(dateValue, formatter));
}

but I still have binding errors:

Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime for property valid_from; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value 2019-01-20; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2019-01-20]

Why don't you use sql Date in your entity and in your database your column sholuld be timestamp without timezone instead of string..and if you need date format why don't you use LocalDate instead of LocalDateTime? If you use LocalDate it's pretty easy to convert to sql Date. :)

You can add custom Serializer and Deserializer to accomplish what you want to do. Define a serializer like below.

public class MyDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

    @Override
    public DateTime deserialize(final JsonParser jsonParser,
                                final DeserializationContext deserializationContext) throws IOException {
        String dateStr = null;
        String timeStr = null;
        String fieldName = null;

        dateStr = jsonParser.getValueAsString();
        if (dateStr != null) {

            return LocalDateTime.parse(dateStr, formatter);
        }
        return null;
     }
}

You can write a deserializer as below.

public class MyDateTimeSerializer extends JsonSerializer<LocalDateTime> {

    private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

    @Override
    public void serialize(final DateTime dateTime,
                          final JsonGenerator jsonGenerator, 
                          final SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(formatter.print(dateTime));
    }   
}

Now you can annotate your datetime fields as below.

@JsonSerialize(using = MyDateTimeSerializer.class)
@JsonDeserialize(using = MyDateTimeDeserializer.class)
private LocalDateTime valid_to;

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