如何创建依赖于消息中的字段的编码器/解码器

时间:2017-05-15 18:43:10

标签: json scala circe

试图使用Circle的用例我如下。 给定一个JSON消息流,我希望在op上匹配并将消息转换为适当的类型。下面的代码显示了所有细节。但是代码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
  }

0 个答案:

没有答案