简体   繁体   English

在带有时间戳的Play框架中将Case类序列化为Json

[英]Serialize Case Class to Json in Play Framework with Timestamp

I'm trying to serialize an object to Json using the play framework, but one of the parameters of the object is a Timestamp object. 我正在尝试使用play框架将对象序列化为Json,但是对象的参数之一是Timestamp对象。 Therefore when I call 所以当我打电话

implicit val eventFormat = Json.format[Event]

I get an error that Timestamp is not serialized. 我收到一个时间戳未序列化的错误。 I know that I could manually write out the Writes function wherein I do each member individually and in turn convert the Timestamp object to a DateTime object, but I was wondering if there were an easier way. 我知道我可以手动写出Writes函数,其中我分别执行每个成员,然后将Timestamp对象转换为DateTime对象,但是我想知道是否有更简单的方法。

I'm ultimately trying to serialize a case class which is a map, mapping a string to an Event and therefore need to serialize the Event as painlessly as possible. 我最终尝试序列化作为映射的case类,将字符串映射到Event,因此需要尽可能轻松地序列化Event。

Try: 尝试:

import java.sql.Timestamp
import org.joda.time.DateTime
import play.api.libs.json._

    object Event {
      implicit val timestampFormat = new Format[Timestamp] {
        def reads(json: JsValue): JsResult[Timestamp] = json match{
          case JsNumber(bigDecimal) =>
            JsSuccess(new Timestamp(bigDecimal.toLong))
          case JsString(txtFormat) =>
            JsSuccess(new Timestamp(DateTime.parse(txtFormat).getMillis))
          case _ =>
            JsError(s"Wrong timestamp format: $json")
        }
        def writes(o: Timestamp): JsValue = JsNumber(o.getTime)
        //def writes(o: Timestamp): JsValue = JsString(new DateTime(o.getTime).toString)
      }
      implicit val eventFormat = Json.format[Event]
    }

    case class Event(timestamp:Timestamp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM