找不到 JsonSupport.this.JF[org.joda.time.LocalDateTime] 类型的证据参数的隐式值

could not find implicit value for evidence parameter of type JsonSupport.this.JF[org.joda.time.LocalDateTime]

我是 spray json 应用程序的初学者,在案例 class 中我使用 LocalDateTime 作为参数类型之一。

import scala.collection.JavaConverters._
import org.apache.commons.imaging.Imaging
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import org.joda.time.{DateTime, LocalDateTime}
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import JodaDateTimeFormats._
import spray.json._

case class ExifMetadata(docName:String, exifOffset:Int, gpsInfo:Int, dateTimeOriginal:LocalDateTime,
                        gpsLatitudeRef:String, gpsLatitude:Double, gpsLongitudeRef:String, gpsLongitude:Double, gpsDateStamp:LocalDateTime)

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val exifMetadataFormat = jsonFormat9(ExifMetadata)
}

但是我不断收到以下错误

could not find implicit value for evidence parameter of type JsonSupport.this.JF[org.joda.time.LocalDateTime]

首先:现在使用 JodaTime 的作者是 discouraged

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

如果您仍然坚持使用 JDK 7(你这个可怜的混蛋),您应该仍然更喜欢使用 ThreeTenBP,它提供的 API 几乎与 JSR-310 相同。这将最大限度地减少升级摩擦。


除此之外:Spray 不提供开箱即用的 JodaTime 类 JsonFormat 个实例。你必须自己写。幸运的是,这并不难。

您希望如何在 JSON 中表示您的 LocalDateTime 取决于您的用例,但标准 ISO 8601 格式是有意义的。

import spray.json._

//prevent confusion with java.time.LocalDateTime
import org.joda.time.{LocalDateTime => JodaLocalDateTime}

implicit val jodaLocalDateTimeFormat: JsonFormat[JodaLocalDateTime] = 
  new JsonFormat[JodaLocalDateTime] {
    override def write(obj: JodaLocalDateTime): JsValue = JsString(obj.toString)

    override def read(json: JsValue): JodaLocalDateTime = json match {
      case JsString(s) => Try(JodaLocalDateTime.parse(s)) match {
        case Success(result) => result
        case Failure(exception) => 
          deserializationError(s"could not parse $s as Joda LocalDateTime", exception)
      }
      case notAJsString => 
        deserializationError(s"expected a String but got a $notAJsString")
    }
  }

Inspiration

确保在 JsonSupport 特征的顶部定义此 JsonFormat。这样,它就可以用于您的其他格式。