json - 将 DateTime 转换为 JSON 字符串

标签 json scala datetime spray spray-json

我想将带有 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/

相关文章:

json - 如何使用 Newtonsoft JSON.NET 执行提供 "paths"的部分对象序列化

json - 在 Flutter 中忽略 jaguar 序列化程序中的空列表

scala - 可以 scala.util.Random.nextInt() : Int occasionally return a negative value?

php - 此功能是否有任何日期/时间可能会中断?

javascript - 当我使用 Node.js 作为 Web 应用程序时,我应该使用 sql 还是 Json 存储数据

python - 无法使用 ijson 访问顶级元素?

scala - 如何在 Play 之外使用 Anorm?

java - Scala 中的多值赋值行为

asp.net - 将日期时间字段格式化为字符串ON 'ToString'格式时,发生“方法 '1'不重载 “dd-MM-yyyy”参数”错误

python - flask-restful 解析器的日期时间格式是什么?