2015-12-15 20 views
0

我想創建JSON序列化器/寫劇本的框架項目解串器,這是我的代碼:JSON序列化器/解串器播放框架

object ClientConnection { 

     /** 
     * Events to/from the client side 
     */ 
     sealed trait ClientEvent 

     case class UserPing() extends ClientEvent 

     /** 
     * Event sent from the client when they have moved 
     */ 
     case class UserMoved(position: Point[LatLng]) extends ClientEvent 

    /** 
     * Formats WebSocket frames to be ClientEvents. 
     */ 
     implicit def clientEventFrameFormatter: FrameFormatter[ClientEvent] = FrameFormatter.jsonFrame.transform(
     clientEvent => Json.toJson(clientEvent), 
     json => Json.fromJson[ClientEvent](json).fold(
      invalid => throw new RuntimeException("Bad client event on WebSocket: " + invalid), 
      valid => valid 
     ) 
    ) 

/** 
    * JSON serialisers/deserialisers for the above messages 
    */ 
    implicit def clientEventFormat: Format[ClientEvent] = Format(
    (__ \ "event").read[String].flatMap { 
     case "user-moved" => UserMoved.userMovedFormat.map(identity) 
     case "user-ping" => UserPing.userPingFormat.map(identity) 
     case other => Reads(_ => JsError("Unknown client event: " + other)) 
    }, 
    Writes { 
     case um: UserMoved => UserMoved.userMovedFormat.writes(um) 
     case pi: UserPing => UserPing.userPingFormat.writes(pi) 
    } 
) 

    object UserMoved { 
    implicit def userMovedFormat: Format[UserMoved] = (
     (__ \ "event").format[String] and 
      (__ \ "position").format[Point[LatLng]] 
    ).apply({ 
     case ("user-moved", position) => UserMoved(position) 
    }, (userMoved: UserMoved) => ("user-moved", userMoved.position)) 
    } 

現在我的問題是,如何我可以映射Ping請求,有一個JSON格式的只有1個鍵是這樣的:

{ "event" : "user-ping"} 

我試圖做到這一點:

object UserPing { 
    implicit def userPingFormat: Format[UserPing] = (
     (__ \ "event").format[String] 
    ).apply({ 
     case ("user-ping") => UserPing() 
    }, (userPing: UserPing) => ("user-ping")) 
    } 

但給我一個錯誤編譯,我該怎麼做?

回答

0

您可以嘗試寫手動自己寫操作

implicit val userPing Writes: Writes[UserPing] = new Writes[UserPing] { 
    def writes(a: UserPing): JsValue = Json.obj("event" -> "user-ping") 
} 

這是你需要什麼?

+0

謝謝你的回答,我已經改變了我的格式化程序,並且我打開了一個新問題:http://stackoverflow.com/questions/34334733/play-framework-frameformatter-with-array-of-object如果你可以幫助我:)謝謝 – Piero