JohnBigs
JohnBigs

Reputation: 2811

Serialize LocalDateTime with play json issue

I have a Person case class:

case class Person(name: String, createdAt: LocalDateTime)

to be able to serialize person object to json so I can return it to the user I have a serualizer:

object PersonSerializer {
  implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

and I import this serializer in the controller so when I can return the result to the use as json like this:

def getPeople: Action[AnyContent] = Action.async {
    peopleDao.getAllPeople.map(people => Ok(Json.toJson(res)))
}

BUT, I get this error:

Error:(39, 55) No instance of play.api.libs.json.Format is available for org.joda.time.LocalDateTime in the implicit scope (Hint: if declared in the same file, make sure it's declared before) implicit val AFormat: OFormat[Account] = Json.format[Account]

How can I fix this?

Upvotes: 0

Views: 1426

Answers (2)

Andriy Plokhotnyuk
Andriy Plokhotnyuk

Reputation: 7989

Another option is using of jsoniter-scala: https://github.com/plokhotnyuk/jsoniter-scala

You will get build in support of java.time.* classes with more than 10x times greater throughput for parsing & serialisation.

Just see results of ArrayOfLocalDateFormatBenchmark for Jsoniter-scala vs. Circe, Jackson and Play-JSON: http://jmh.morethan.io/?source=https://plokhotnyuk.github.io/jsoniter-scala/oraclejdk8.json

Upvotes: 0

Francis Toth
Francis Toth

Reputation: 1685

Your answer is pretty much in the stacktrace. Basically, in order to format a Person, Play's serializer needs to know how to serialize a LocalDateTime. You should try something like:

object PersonSerializer {
    implicit val LocalDateFormat: OFormat[LocalDateFormat] = 
        new OFormat[LocalDateFormat](){ /*...*/ }
    implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

I suggest you to look at this post, this one, and the documentation.

Upvotes: 2

Related Questions