1

我正在尝试使用circe在 Akka-Http 应用程序中进行 JSON(反)序列化,而不是 spray-json。出于这个原因,我想使用entity指令 withas[String]来获取请求正文的字符串表示,然后进行我自己的反序列化。但它似乎entity太聪明了,它拒绝任何没有 Content-Type 的东西text/plain

我对文档的理解是,隐式魔法应该让我能够执行以下操作:

import akka.http.scaladsl.model.ContentTypes
entity(as[String].forContentTypes(ContentTypes.`application/json`))

但是编译器并没有做所有的事情来推断我想要as解析为 a FromEntityUnmarshaller[String],它具有隐式方法forContentTypes,其结果应该转换为 a FromMessageUnmarshaller[String],(由于逆变)应该满足对 a 的需要FromRequestUnmarshaller[String]

但是,即使通过以下方式握住编译器:

val jsonRequestToStringUnmarshaller: FromRequestUnmarshaller[String] = 
  messageUnmarshallerFromEntityUnmarshaller(implicitly[FromEntityUnmarshaller[String]].forContentTypes(ContentTypes.`application/json`))
entity(jsonRequestToStringUnmarshaller)

我的服务器仍在拒绝application/json请求。

是什么赋予了?

更新

我现在可以看到我误解forContentTypes了,它只会缩小而不是扩大 Unmarshaller 将接受的 Content-Type 范围。这只是解释了为什么我的解决方案不起作用。

4

1 回答 1

1

我建议使用引擎盖下的 circe 将 Akka-Http 直接编组器从 / 到所需的类型。

它可能看起来像:https ://github.com/PDXostc/rvi_sota_server/blob/master/common/src/main/scala/org/genivi/sota/marshalling/CirceMarshallingSupport.scala

于 2016-01-11T19:32:20.203 回答