3

我尝试使用 Circle 的用例如下。给定一个 JSON 消息流,我想在操作上匹配并将消息从适当的类型转换为适当的类型。下面的代码显示了所有细节。然而,代码 des 无法编译,因为它需要不同 ResponseMessag:es 的隐式编码器。

为什么使用import io.circe.generic.auto._获取不同ResponseMessage类型的编码器和解码器然后只编写自定义是不够的ResponseMessage?如何更改下面的示例以使测试通过? 有没有办法不必将ResponseOpType 的不同值解码为字符串,我想要一个trait层次结构,但它以错误的格式解码(作为 JSON 对象而不仅仅是纯字符串)?

object OpTypes {
  type ResponseOpType = String
  val Connection: ResponseOpType = "connection"
  val Status: ResponseOpType = "status"
}
import OpTypes._

sealed trait ResponseMessage {
  /* The operation type */
  def op: ResponseOpType
  /* Client generated unique id to link request with response (like json rpc) */
  def id: Integer
}

case class ConnectionMessage (
                               op: ResponseOpType,
                               id: Integer,
                               /* The connection id */
                               connectionId: String
                             ) extends ResponseMessage

case class StatusMessage (
                           op: ResponseOpType,
                           id: Integer,
                           /* Additional message in case of a failure */
                           errorMessage: String,
                           /* The type of error in case of a failure */
                           errorCode: String,
                           /* The connection id */
                           connectionId: String,
                           /* Is the connection now closed */
                           connectionClosed: Boolean,
                           /* The status of the last request */
                           statusCode: String
                         ) extends ResponseMessage

case class UnableToParseStreamResponseMessage (op:String="Error", id:Integer = 0) extends ResponseMessage

  test("Circle support") {
    import io.circe.{Decoder, Encoder}
    import io.circe.generic.auto._
    import io.circe.syntax._
    import io.circe.parser.decode

    implicit val decodeResponseMessage: Decoder[ResponseMessage] = Decoder.instance(c => {
      c.get[OpTypes.ResponseOpType]("op").flatMap {
        case OpTypes.Connection => c.as[ConnectionMessage]
        case OpTypes.Status => c.as[StatusMessage]
        case _ => c.as[UnableToParseStreamResponseMessage]
      }
    })

    implicit val encodeResponseMessage: Encoder[ResponseMessage] = new Encoder[ResponseMessage] {
      final def apply(a: ResponseMessage): Json = Json.obj(
        //Im encoding ResponseMessage wich only have a subset of all the parameters I need???
      )
    }

    val originalJson =
      """
        |{"op":"connection",
        | "id":1,
        | "connectionId":"1"
        | }
      """.stripMargin
    val original = ConnectionMessage(op ="connection", id = 1, connectionId = "1")

    decode[ResponseMessage](originalJson) shouldBe original
    originalJson shouldBe original.asJson.noSpaces
  }
4

0 回答 0