0

How to create wrapper for Json4s? Default json4s formater date converted all to SimpleDateFormat. I want convert all date field to unixtime format.

Rinat Mukhamedgaliev
  • 5,401
  • 8
  • 41
  • 59

2 Answers2

-1

You should be able to implement your own Formats. Here is a simplified example, which is based on the SerializationExamples.

EDIT: updated example

import java.util.Date
import org.json4s._
import org.json4s.jackson.Serialization

object Main extends App {

  implicit val formats = new DefaultFormats {
    override val dateFormat: DateFormat = new DateFormat {
      override def parse(s: String): Option[Date] = Some(new Date(s.toLong * 1000))
      override def format(d: Date): String = (d.getTime/1000).toString
    }
  }

  case class Lotto(id: Long, drawDate: Date)

  val lotto = Lotto(3L, new Date())

  val ser: String = Serialization.write(lotto)
  println(ser) // prints value 'drawDate' as unix time
  println(Serialization.read[Lotto](ser)) // prints deserialized Lotto instance
}
edi
  • 3,112
  • 21
  • 16
-1

If your project allow it... instead of writing any new piece of code, why no to use moment.js. It certainly give you the option to have unix output there.

unix function in moment.js

Chasky
  • 60
  • 6
  • I write not only JS. And string as dates sucks. – Rinat Mukhamedgaliev Jan 11 '15 at 21:50
  • momentjs is just a way to manipulate the date, you can always have it back for internal storing in date datatype. Down voter, nice to know the reason so I can try to improve the answer... which besides was more of a comment... but I didn't have the privileges before :) ... or to have a better non-opinion based question :) – Chasky Jan 14 '15 at 09:06