我想为Play Framework项目创建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 :(得分:0)
您可以尝试手动编写自己的写作
New Launch Configuration
这是你需要的吗?