Converting types when using play json writesAsk Question


Following on from this question Applying conversion to play framework json element before applying to class

I have a Date object which I want to be written to a string in json in a specific format.

implicit val tokenWrites: Writes[Token] = (
  (JsPath \ "creation_date").write[Date] and
  (JsPath \ "expires").writeNullable[Date]

Which I want to be json'ed as:

"creation_date": "2014-05-22T08:05:57.556385+00:00"

To convert the string to a Date I have used:

def strToDate(string2: String): Date = {
  val df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

And then mapped in the reads, but this doesn't seem to be possible with a write


Follow definition of write

def write[T](implicit w: Writes[T])

you can create own Writes[T] and use it.

For example

object dateWrite extends Writes[Date] {
  override def writes(o: Date): JsValue = JsString("some formatted date")

will write o:Date to JsString("some formatted date") (you can use own format: Date => JsValue), and then use own Writes[T] in write:

implicit val tokenWrites: Writes[Token] = (
  (JsPath \ "creation_date").write[Date](dateWrite) and
    (JsPath \ "expires").writeNullable[Date](dateWrite)
  ) (unlift(Token.unapply))

As a result

tokenWrites.writes(Token(new Date(), Some(new Date())))

will be

res1: play.api.libs.json.JsValue = {"creation_date":"some formatted date","expires":"some formatted date"}
标签: scala playframework playframework-2.0
© 2014 TuiCode, Inc.