无法使用Scala Circle json库中的LocalDateTime的自定义解码器反序列化对象

时间:2018-10-16 20:34:39

标签: json scala

我试图将自定义反序列化器添加到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案例类?

1 个答案:

答案 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]
}