我想将带有 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)))
最佳答案
这里有几个问题。
首先,AbstractDateTime 中的 toString() 方法需要一个或多个参数,参见 here .
但我建议您不要走这条路,并建议您正确使用 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 格式,请根据需要进行调整。
关于json - 将 DateTime 转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178108/