How can I parse a string of YYYY-MM-dd
to java.time.LocalDate
? Currently I have tried the following approaches:
JavaTimeSerializers
throws Error JString cannot be converted to LocalDate
case class Dates(createdAt: LocalDate, updatedAt: LocalDate, startDate: LocalDate, endDate: LocalDate )
implicit val formats = defaultFormats ++ org.json4s.ext.JavaTimeSerializers.all
implicit val formats = defaultFormats ++ org.json4s.ext.JavaTimeSerializers.all
val input =
"""
|{
| "createdAt": "1999-12-10",
| "updatedAt": "1999-12-16",
| "startDate": "2000-01-02",
| "endDate": "200-01-16"
|}
""".stripMargin
val result = read[Dates] { input }
DefaultFormats
:throws error found java.time.format.DateTimeFormatter expected java.text.SimpleDateFormat
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd")
}
val input =
"""
|{
| "createdAt": "1999-12-10",
| "updatedAt": "1999-12-16",
| "startDate": "2000-01-02",
| "endDate": "200-01-16"
|}
""".stripMargin
val result = read[Dates] { input }
CustomFormatter
based on example hereError Expected type was: (PartialFunction[org.json4s.JValue,java.time.LocalDate], PartialFunction[Any,org.json4s.JValue])
object LocalDateSerializer extends CustomSerializer[LocalDate](
format => (
{
case JString(str) => LocalTime.parse(str)
case JNull => null
}
))
implicit val formats = org.json4s.DefaultFormats ++ new LocalDateSerializer
For your third error, You are missing the second Partial Function, see:
ser: Formats => (PartialFunction[JValue, A], PartialFunction[Any, JValue])
so you maybe you want do it, like:
object LocalDateSerializer extends CustomSerializer[LocalDate](format => ({
case JString(str) =>
LocalDate.parse(str)
}, {
case date: LocalDate => JString(date.toString)
}))
and Since the LocalDate
default pattern is yyyy-MM-dd
, so "200-01-16"
this is not a legal time, you maybe want to change it to 2000-01-16
.