Search code examples
jsonscalajson4s

Json4s date to unixtimestamp


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


Solution

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