2

我想将带有Option[DateTime]参数的案例类转换为可以由 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))
    )
  }
}

但我得到:

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))

当我尝试编译它时,无论我尝试什么,我似乎都无法将 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)))
4

1 回答 1

10

你在这里有几个问题。

首先,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 ...")
    }
  }

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

于 2014-08-07T09:49:28.563 回答