我有一个 Grails 3.1.2 应用程序
我的域类之一是 Goal
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
class Goal {
String name
String description
LocalDateTime targetDate
Date dateCreated
Date lastUpdated
static constraints = {
name(nullable: false, blank: false)
}
}
当我在 Goal 实例上调用 validate 时,我得到:
- 字段“targetDate”上的对象“com.liftyourgame.model.Goal”中出现字段错误:值被拒绝 [2016-01-28T15:10:39.000Z];代码 [com.liftyourgame.model.Goal.targetDate.typeMismatch.error,com.liftyourgame.model.Goal.targetDate.typeMismatch,goal.targetDate.typeMismatch.error,goal.targetDate.typeMismatch,typeMismatch.com.liftyourgame.model。 Goal.targetDate,typeMismatch.targetDate,typeMismatch.java.time.LocalDateTime,typeMismatch];参数 [目标日期];默认消息[找不到匹配的构造函数:java.time.LocalDateTime(java.lang.String)]
如何更改验证以便不需要此构造函数?
最佳答案
How can I change the validation so it doesn't need this constructor?
你不能,但验证并不是真正的问题。数据绑定(bind)器就是问题所在。默认 Binder 尚未内置对 LocalDateTime
的支持。
您可以像这样注册自己的转换器:
转换器:
// src/main/groovy/demo/MyDateTimeConverter.groovy
package demo
import grails.databinding.converters.ValueConverter
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class MyDateTimeConverter implements ValueConverter {
@Override
boolean canConvert(Object value) {
value instanceof String
}
@Override
Object convert(Object value) {
def fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
LocalDateTime.parse(value, fmt)
}
@Override
Class<?> getTargetType() {
LocalDateTime
}
}
将其注册为 Bean:
// grails-app/conf/spring/resources.groovy
beans = {
myConverter demo.MyDateTimeConverter
}
关于java - 找不到 : java. time.LocalDateTime(java.lang.String) 的匹配构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785999/