mtrebi
mtrebi

Reputation: 267

Spray: Marshalling UUID to JSON

I'm having some problems marshalling from UUID to JSON

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

The signature of my class:

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

val json4sFormats = DefaultFormats.

This gives me :

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

instead of:

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

So, how can I add a UUID format to json4sFormats to marshall UUID's correctly?? In other cases I mix in with a trait that have this function:

 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)
   }
 }

But here I'm not able to because I don't have declared a spray.json.RootJsonReader and/or spray.json.RootJsonWriter for every type T and does not compile. (See complete function T <: AnyRef)

Thanks.

Upvotes: 0

Views: 1069

Answers (1)

mtrebi
mtrebi

Reputation: 267

I solved it! If someone has the same problem take a look here

I defined my own UUID Serializer as follows:

 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)))
  }
  ))

And now it's working!

Upvotes: 2

Related Questions