喷json隐式UUID转换

时间:2015-07-14 12:38:28

标签: scala spray-json

我有一个用户模型

case class User(name: String, email: String, password: Option[String] = None, key: Option[UUID] = None)

使用喷雾json marshaller

object UserJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
  implicit val userFormat = jsonFormat4(User)
}

直到我将关键字段从Option[String]转换为Option[UUID]并且我现在收到两个编译错误时,它才有效:

Error:(8, 40) could not find implicit value for evidence parameter of type in.putfood.http.UserJsonSupport.JF[Option[java.util.UUID]]
  implicit val userFormat = jsonFormat4(User)
                                       ^
Error:(8, 40) not enough arguments for method jsonFormat4: (implicit evidence$16: in.putfood.http.UserJsonSupport.JF[String], implicit evidence$17: in.putfood.http.UserJsonSupport.JF[String], implicit evidence$18: in.putfood.http.UserJsonSupport.JF[Option[String]], implicit evidence$19: in.putfood.http.UserJsonSupport.JF[Option[java.util.UUID]], implicit evidence$20: ClassManifest[in.putfood.model.User])spray.json.RootJsonFormat[in.putfood.model.User].
Unspecified value parameters evidence$19, evidence$20.
  implicit val userFormat = jsonFormat4(User)
                                   ^

我的理解是,自this issue解决以来,它应该只需要提供我自己的UUID反序列化器就可以工作。我错了还是完全不同意?

是否有可能不想进入Option

1 个答案:

答案 0 :(得分:4)

它可能应该已经解决,但是,我最近遇到了同样的问题(使用akka-http v10.0.0时)我能够通过定义以下内容来解决它

  implicit object UUIDFormat extends JsonFormat[UUID] {
    def write(uuid: UUID) = JsString(uuid.toString)
    def read(value: JsValue) = {
      value match {
        case JsString(uuid) => UUID.fromString(uuid)
        case _              => throw new DeserializationException("Expected hexadecimal UUID string")
      }
    }
  }

解决方案来自Fidesmo API

更新

我添加了一个经历最常见用例的库。 < Link here>