喷涂:将UUID编组为JSON

时间:2014-05-12 18:34:59

标签: json scala marshalling spray

我在从UUID编组到JSON时遇到了一些问题

  def complete[T <: AnyRef](status: StatusCode, obj: T) = {
    r.complete(status, obj)     // Completes the Request with the T obj result!
  }
          ^

我班级的签名:

trait PerRequest extends Actor
with Json4sSupport
with Directives
with UnrestrictedStash
with ActorLogging {

val json4sFormats = DefaultFormats.

这给了我:

    "id": {
        "mostSigBits": -5052114364077765000,
        "leastSigBits": -7198432257767597000
    },

而不是:

    "id": "b9e348c0-cc7f-11e3-9c1a-0800200c9a66"

那么,我怎样才能将UUID格式添加到json4sFormats来正确编组UUID?在其他情况下,我混入具有此功能的特征:

 implicit object UuidJsonFormat extends RootJsonFormat[UUID] {
   def write(x: UUID) = JsString(x.toString)
   def read(value: JsValue) = value match {
     case JsString(x) => UUID.fromString(x)
     case x           => deserializationError("Expected UUID as JsString, but got " + x)
   }
 }

但是我不能这样做因为我没有为每个类型T声明一个spray.json.RootJsonReader和/或spray.json.RootJsonWriter而且没有编译。 (参见完整函数T&lt;:AnyRef)

感谢。

1 个答案:

答案 0 :(得分:2)

我解决了!如果有人遇到同样的问题,请查看here

我将自己的UUID Serializer定义如下:

 class UUIDSerializer extends CustomSerializer[UUID](format => (
  {
   case JObject(JField("mostSigBits", JInt(s)) :: JField("leastSigBits", JInt(e)) :: Nil) =>
      new UUID(s.longValue, e.longValue)
  },
  {
    case x: UUID =>  JObject(JField("id", JString(x.toString)))
  }
  ))

现在它正在运作!