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.
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.