Domanda

Im having some problems returning an UUID in a JSON with my application in Scala and Spray. When the entity User(id: UUID, name: String) is parsed to JSON I received:

 {
     "id": {
         "mostSigBits": 1310448748437770800,
         "leastSigBits": -7019414172579620000
      },
      "name": "Sharekhan"
 }

I would like to receive the uuid in a String format. Something like:

 {
     "id": "122fa631-92fd-11e2-9e96-0800200c9a63",
      "name": "Sharekhan"
 }

I defined the UUID format and the Read is executed when I parse from JSON to User but the Write isn't used in the inverse order (User -> Json)

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

Is any way to do this o should I convert the UUID into a String in the User entity?

Any help will be appreciated,

Thanks.

È stato utile?

Soluzione

Make sure to have the implicit format for the Uuid before the user format that uses it and it should work:

object UserJsonProtocol extends DefaultJsonProtocol {
 implicit object UuidJsonFormat extends RootJsonFormat[UUID] {
   def write(x: UUID) = JsString(x.toString) //Never execute this line
   def read(value: JsValue) = value match {
      case JsString(x) => UUID.fromString(x)
      case x           => deserializationError("Expected UUID as JsString, but got " + x)
   }
 }
 implicit val UserFormat = jsonFormat2(User)
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top