我在使用UUID
和JSON
中的应用程序返回Scala
Spray
时遇到了一些问题。
当实体User(id: UUID, name: String)
被解析为JSON
时,我收到了:
{
"id": {
"mostSigBits": 1310448748437770800,
"leastSigBits": -7019414172579620000
},
"name": "Sharekhan"
}
我希望收到uuid
中的String format
。类似的东西:
{
"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转换为用户实体中的字符串吗?
任何帮助将不胜感激,
感谢。
答案 0 :(得分:0)
确保在使用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)
}