【发布时间】:2015-12-15 08:25:39
【问题描述】:
我想为 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"))
}
但是编译时给我报错,怎么办?
【问题讨论】:
标签: json playframework playframework-2.0