【问题标题】:JSON serialisers/deserialisers Play FrameworkJSON 序列化器/反序列化器 Play Framework
【发布时间】: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


    【解决方案1】:

    您可以尝试手动编写自己的 Writes

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

    这是你需要的吗?

    【讨论】:

    猜你喜欢
    • 2014-07-12
    • 2017-07-28
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2015-11-22
    • 2015-10-29
    相关资源
    最近更新 更多