我在Scala
和Spray
的应用程序中返回JSON
中的UUID
有一些问题。当实体User(id: UUID, name: String)
被解析为JSON
时,我收到:
{
"id": {
"mostSigBits": 1310448748437770800,
"leastSigBits": -7019414172579620000
},
"name": "Sharekhan"
}
我希望收到String format
中的uuid
。比如:
{
"id": "122fa631-92fd-11e2-9e96-0800200c9a63",
"name": "Sharekhan"
}
我定义了UUID格式,当我从JSON
解析到User
时执行Read,但Write不以相反的顺序使用(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)
}
}
是否有任何方法可以做到这一点?我应该将UUID转换为用户实体中的字符串吗?
任何帮助都将不胜感激,
谢谢。
确保Uuid的隐式格式在使用它的用户格式之前,它应该工作:
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)
}