如何为Json4s创建包装器?默认的json4s格式化程序日期转换为SimpleDateFormat。我希望将所有日期字段转换为unixtime格式。
发布于 2015-01-07 19:29:42
您应该能够实现自己的Formats。下面是一个基于SerializationExamples的简化示例。
编辑:更新的示例
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
}发布于 2015-01-09 13:21:26
如果你的项目允许..。而不是编写任何新的代码,为什么不使用moment.js。它确实为您提供了让unix输出的选项。
moment.js中的unix函数
https://stackoverflow.com/questions/27824458
复制相似问题