本文介绍了如何在后台实现Akka HTTP封送处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将编译以下Scala代码:
The following Scala code compiles:
的对象p>
SprayJsonSupport is the object where implicit Marshallers are defined and they are the ones which gives Marshallable
package akka.http.scaladsl.marshallers.sprayjson trait SprayJsonSupport { implicit def sprayJsonMarshallerConverter[T](writer: RootJsonWriter[T])(implicit printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[T] = sprayJsonMarshaller[T](writer, printer) implicit def sprayJsonMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[T] = sprayJsValueMarshaller compose writer.write implicit def sprayJsValueMarshaller(implicit printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[JsValue] = Marshaller.StringMarshaller.wrap(MediaTypes.`application/json`)(printer) }如果不要导入 SprayJsonSupport ,您将不会得到隐式的 Marshallers ,它将您的案例类编组为所需的输出,即 JSObject 。
If you don't import SprayJsonSupport, you won't get implicit Marshallers which marshall your case class to desired output which is JSObject.
如果您不想导入 SprayJsonSupport 为JsonMarshallers提供默认设置,编写您自己的文件或从 JsonSpraySupport 复制粘贴这些编组。
If you don't want to import SprayJsonSupport that provides default toJsonMarshallers, write your own, or copy paste the marshallers from JsonSpraySupport.
示例
object GetHttpRoutes { case class Acknowledge(status: String) implicit val itemFormat = jsonFormat1(Acknowledge) implicit def toJsonMarshallerConverter[Entity](writer: RootJsonWriter[Entity])(implicit printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[Entity] = toJsonMarshaller[Entity](writer, printer) implicit def toJsonMarshaller[Entity](implicit writer: RootJsonWriter[Entity], printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[Entity] = toJsValueMarshaller compose writer.write implicit def toJsValueMarshaller(implicit printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[JsValue] = Marshaller.StringMarshaller.wrap(MediaTypes.`application/json`)(printer) val get_api = path("") { get { context => context.complete { Acknowledge(status = "xbox") } } } } trait HTTPRoutes { implicit val system: ActorSystem implicit val materializer: ActorMaterializer val route = GetHttpRoutes.get_api }测试
class GetHttpRoutesCompSpecs extends WordSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll { "HTTP GET endpoints" should { "returns xbox on /" in { Get("/") ~> GetHttpRoutes.get_api ~> check { responseAs[String] shouldEqual """{"status":"xbox"}""" } } } }这篇关于如何在后台实现Akka HTTP封送处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!