我正在使用play.api.libs.json._库。我有这种Scala类。我需要以Json格式读/写这个类。因为Timestamp没有隐式的读/写器。我必须提供自己的。不幸的是,我尝试了几种方式。你能告诉我它是怎么做的吗?提前致谢!
case class Event(id: Long, startTime: Option[java.sql.Timestamp] = None, endTime: Option[java.sql.Timestamp] = None)
我想按照Json格式POST / GET
{
"id": 1,
"startTime": "2011-10-02 18:48:05.123456",
"endTime": "2011-10-02 20:48:05.123456"
}
答案 0 :(得分:7)
只需在Json Reader或Json Format for Event class
之前添加import play.api.libs.json.Json._
import play.api.libs.json._
def timestampToDateTime(t: Timestamp): DateTime = new DateTime(t.getTime)
def dateTimeToTimestamp(dt: DateTime): Timestamp = new Timestamp(dt.getMillis)
implicit val timestampFormat = new Format[Timestamp] {
def writes(t: Timestamp): JsValue = toJson(timestampToDateTime(t))
def reads(json: JsValue): JsResult[Timestamp] = fromJson[DateTime](json).map(dateTimeToTimestamp)
}
答案 1 :(得分:3)
我为个人项目编写的代码:
implicit object timestampFormat extends Format[Timestamp] {
val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'")
def reads(json: JsValue) = {
val str = json.as[String]
JsSuccess(new Timestamp(format.parse(str).getTime))
}
def writes(ts: Timestamp) = JsString(format.format(ts))
}
不要忘记导入此内容:
import java.sql.Timestamp
import java.text.SimpleDateFormat
import play.api.Play.current
import play.api.libs.json._
它尊重Javascript日期标准。
来源:https://github.com/BinaryBrain/Gamers/blob/master/server/play/app/models/Package.scala