2014-05-12 81 views
0

我有一些问题编组从UUID到JSON喷雾:编组UUID以JSON

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

我班上的签名:

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

val json4sFormats = DefaultFormats. 

这给了我:

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

而不是:

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

那么,如何添加一个UUID格式到json4sFormats来编组UUID的正确?在其他情况下,我在混合与性状具有此功能:

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

但在这里我不能,因为我没有宣布spray.json.RootJsonReader和/或spray.json.RootJsonWriter对于每个类型T并且不编译。 (见完整功能T <:AnyRef)

谢谢。

回答

2

我解决了它!如果有人有相同的问题就来看看here

我定义我自己UUID Serializer如下:

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

而现在它的工作!