score:24

Accepted answer

Expecting a better alternative, here my workaround:

val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

val jodaDateReads = Reads[DateTime](js =>
  js.validate[String].map[DateTime](dtString =>
    DateTime.parse(dtString, DateTimeFormat.forPattern(dateFormat))
  )
)

val jodaDateWrites: Writes[DateTime] = new Writes[DateTime] {
  def writes(d: DateTime): JsValue = JsString(d.toString())
}

val userReads: Reads[User] = (
  (JsPath \ "name").read[String] and
    (JsPath \ "created").read[DateTime](jodaDateReads)
  )(User.apply _)

val userWrites: Writes[User] = (
  (JsPath \ "name").write[String] and
   (JsPath \ "created").write[DateTime](jodaDateWrites)
  )(unlift(User.unapply))

implicit val userFormat: Format[User] = Format(userReads, userWrites)

score:1

I think you should set the User type in Json.toJson and Json.fromJson functions. Instead of

println(Json.toJson(new User("user", new DateTime())))
println(Json.fromJson(value))

try:

println(Json.toJson[User](new User("user", new DateTime())))
println(Json.fromJson[User](value))

When you set the type explicitly framework will know what reads/writes to use.

Update: It is not necessarily to set type for Json.toJson function because you pass User object as function argument and framework determines the type in runtime. But for Json.fromJson[User] you must set the type, otherwise framework doesn't know type of the object you want to read.

score:6

I know this question has been answered for a while, but I found a more concise answer

val pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
implicit val dateFormat = Format[DateTime](Reads.jodaDateReads(pattern), Writes.jodaDateWrites(pattern))
implicit val userFormat = Json.format[User]

score:24

In play 2.6, the canonical way to serialize/deserialize joda DateTime json is by using the play-json-joda library. Import the library by updating your build.sbt. Then create json reader and json writers like this :

import play.api.libs.json.JodaWrites
implicit val dateTimeWriter: Writes[DateTime] = JodaWrites.jodaDateWrites("dd/MM/yyyy HH:mm:ss")
import play.api.libs.json.JodaReads
implicit val dateTimeJsReader = JodaReads.jodaDateReads("yyyyMMddHHmmss")

Related Query

More Query from same tag