Json 如何根据circe消息中的字段创建编码器/解码器
我尝试使用Circle的用例如下。 给定一个JSON消息流,我希望在op上进行匹配,并将消息从和转换为适当的类型。下面的代码显示了所有详细信息。但是,代码des无法编译,因为它需要为不同的responseMessage:es使用隐式编码器 为什么使用Json 如何根据circe消息中的字段创建编码器/解码器,json,scala,circe,Json,Scala,Circe,我尝试使用Circle的用例如下。 给定一个JSON消息流,我希望在op上进行匹配,并将消息从和转换为适当的类型。下面的代码显示了所有详细信息。但是,代码des无法编译,因为它需要为不同的responseMessage:es使用隐式编码器 为什么使用导入io.circe.generic.auto.\u获取 不同响应消息类型的编码器和解码器,然后 仅为响应消息编写自定义消息?我怎样才能改变这个例子 让测试通过? 有没有一种方法不必将responseType的不同值解码为字符串,我想要一个trait
导入io.circe.generic.auto.\u
获取
不同响应消息
类型的编码器和解码器,然后
仅为响应消息编写自定义消息
?我怎样才能改变这个例子
让测试通过?
有没有一种方法不必将responseType的不同值解码为字符串,我想要一个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
}