Search code examples
jsonscalajava-timejson4s

Parsing string in json to java.time.LocalTime using json4s


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

Solution

  • 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.