将DateTime转换为JSON字符串

for*_*ash 2 datetime json scala spray spray-json

我想将带有Option[DateTime]参数的case类转换为可由API提供的spray-json对象.使用spray-json我有一个自定义的JsonFormat

object JsonImplicits extends DefaultJsonProtocol {
  implicit object PostJsonFormat extends RootJsonFormat[Post] {

    def write(p: Post) = JsObject(
      "title" -> JsString(p.title),
      "content" -> JsString(p.content),
      "author" -> JsString(p.author),
      "creationDate" -> JsString(p.creationDate.getOrElse(DateTime.now))
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

但我得到:

overloaded method value apply with alternatives:
  (value: String)spray.json.JsString <and>
  (value: Symbol)spray.json.JsString
  cannot be applied to (com.github.nscala_time.time.Imports.DateTime)
    "creationDate" -> JsString(p.creationDate.getOrElse(DateTime.now))
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,无论我尝试什么,我似乎无法将DateTime对象转换为字符串.例如,当我试着打电话时,toString我得到了

ambiguous reference to overloaded definition,
  both method toString in class AbstractDateTime of type (x$1: String, x$2: java.util.Locale)String
  and  method toString in class AbstractDateTime of type (x$1: String)String
  match expected type ?
    "creationDate" -> JsString(p.creationDate.getOrElse(DateTime.now.toString)))
Run Code Online (Sandbox Code Playgroud)

Arn*_*lay 7

你有几个问题.

首先,AbstractDateTime中的toString()方法需要一个或多个参数,请参见此处.

但我会建议你反对这条道路并建议正确使用Spray-Json.

Spray-json不知道如何序列化Option[DateTime],因此你必须RootJsonFormat为它提供一个.

这就是我在做的事情.

implicit object DateJsonFormat extends RootJsonFormat[DateTime] {

    private val parserISO : DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();

    override def write(obj: DateTime) = JsString(parserISO.print(obj))

    override def read(json: JsValue) : DateTime = json match {
      case JsString(s) => parserISO.parseDateTime(s)
      case _ => throw new DeserializationException("Error info you want here ...")
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果您不想使用ISO格式,请根据需要进行调整.