Spray JSON隐式UUID转换

7

我有一个用户模型

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

使用spray-json编组器
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)
                                   ^

我的理解是,自从这个问题得到解决以来,它应该能够在不需要提供自己的UUID反序列化程序的情况下正常工作。我错了还是还有其他原因?
它可能不喜欢被放在Option内部吗?
2个回答

6

这个问题本来应该被解决的,但是我最近遇到了同样的问题(当我使用 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借鉴来的。


更新:

我添加了一个库,可以处理最常见的用例。 <链接在此处>


0

提到的问题涉及到一个已关闭而非合并的PR。原因也在那里提供:

I want to cancel this Pull Request – there are instances where non-String serialisation is useful.

In scalad, we're creating custom marshallers for Date and UUID so that the Mongo backend can serialise them correctly.

所以,请遵循mamdouh的答案。创建自定义格式并不是什么大问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接