Akka http(联合国)马歇尔特质 [英] akka http (un)marshall traits

查看:96
本文介绍了Akka http(联合国)马歇尔特质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设以下代码:

sealed trait Action {
    def run(): Boolean
}

case class SimpleAction(parameter: String) extends Actions {
 // some impl
}

case class ExtendedAction(parameter1: String, parameter2: String) extends Actions {
 // some impl
}

现在我想定义一个可以检索操作的Web服务。我该如何将动作编组,因为它只是特征而不是特定类型?

Now I want to define a webservice where one can retrieve the Actions. How can I Marshall the Action as it's just the trait and no specific Type?

我发现了这个 https://github.com/spray/spray-json#providing-jsonformats-for-other-types 文件。有没有比使用这种方法和模式匹配更简单的方法了?

I have found this https://github.com/spray/spray-json#providing-jsonformats-for-other-types in the Docs. Is there any simpler way to achieve this than using this approach mixed with pattern matching?

推荐答案

import spray.json._
import DefaultJsonProtocol._

implicit val simpleActionFormat = jsonFormat1(SimpleAction)
implicit val extendedActionFormat = jsonFormat2(ExtendedAction)
implicit val actionFormat1 = new JsonFormat[Action] {
  override def write(obj: Action): JsValue = obj match {
    case a: SimpleAction => JsObject("type" -> "simple".toJson, "value" -> a.toJson)
    case b: ExtendedAction => JsObject("type" -> "extended".toJson, "value" -> b.toJson)
  }

  override def read(json: JsValue): Action = json.asJsObject.getFields("type", "value") match {
    case Seq(JsString("simple"), js) => js.convertTo[SimpleAction]
    case Seq(JsString("extended"), js) => js.convertTo[ExtendedAction]
    case _ => throw new RuntimeException(s"Invalid json format: $json")
  }
}

或者,如果您只关心将 Actions 转换为json,则只需:

Or if you only care about converting Actions to json, then simply:

implicit val simpleActionFormat = jsonFormat1(SimpleAction)
implicit val extendedActionFormat = jsonFormat2(ExtendedAction)
implicit val actionFormat = lift(new JsonWriter[Action] {
  override def write(obj: Action): JsValue = obj match {
    case a: SimpleAction => a.toJson
    case b: ExtendedAction => b.toJson
  }
})

这篇关于Akka http(联合国)马歇尔特质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆