我试图将自定义反序列化器添加到LocalDateTime
对象的case类中,但是它从circe-java8
模块中提取了默认的反序列化器。如果删除此模块,则代码将无法编译(找不到LocalDateTime
的反序列化器)
sbt
"io.circe" %% "circe-core" % circeVersion,
"io.circe" %% "circe-generic" % circeVersion,
"io.circe" %% "circe-parser" % circeVersion,
"io.circe" %% "circe-optics" % circeVersion,
"io.circe" %% "circe-java8" % circeVersion,
带有自定义LocalDateTime
序列化器/反序列化器的源代码
case class A(
date: LocalDateTime,
)
object A {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
implicit val dateEncoder = Encoder.encodeString.contramap[LocalDateTime](_.format(formatter))
implicit val dateDecoder = Decoder.decodeString.emap[LocalDateTime](str => {
Either.catchNonFatal(LocalDateTime.parse(str, formatter)).leftMap(_.getMessage)
})
}
如何将对象LocalDateTime
中指定的A
对象的自定义解串器应用于A
案例类?
答案 0 :(得分:2)
对A
使用半自动推导:
import io.circe.generic.semiauto._
case class A(
date: LocalDateTime,
)
object A {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
implicit val dateEncoder = Encoder.encodeString.contramap[LocalDateTime](_.format(formatter))
implicit val dateDecoder = Decoder.decodeString.emap[LocalDateTime](str => {
Either.catchNonFatal(LocalDateTime.parse(str, formatter)).leftMap(_.getMessage)
})
implicit val AEncoder = deriveEncoder[A]
implicit val ADecoder = deriveDecoder[A]
}