3

How can I parse a string of YYYY-MM-dd to java.time.LocalDate? Currently I have tried the following approaches:

  1. import 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 }
  1. override 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 }
  1. try to define CustomFormatter based on example here

Error 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
Community
  • 1
  • 1
vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

1 Answers1

4

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.

chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • thanks, the corrected code lives [here](https://github.com/vamsiampolu/scalaexercises/blob/master/src/test/scala/example/Json4sSpec.scala) – vamsiampolu Dec 19 '17 at 06:07