json - 如何将自定义编码器添加到 akka http?

标签 json scala marshalling spray akka-http

作为 scala 和 akka-http 的初学者,我正在尝试加入序列化 aka 编码过程。

该项目使用 akka@2.5.2 和 akka-http@10.0.10"。此外,它还包含 akka-http-spray-json 依赖项。

在代码库中,我们使用 Java.Util.Currency (它可能已被弃用,这并不重要,因为我仍然想知道如何添加自定义编码器。)

鉴于此示例 Controller :

def getCurrencyExample: Route = {
    path("currencyExample") {
      val currency: Currency = Currency.getInstance("EUR")
      val code: String = currency.getCurrencyCode

      val shouldBeFormated = collection.immutable.HashMap(
        "currencyCode" -> code,
        "currencyObject" -> currency
      )

      complete(shouldBeFormated)
    }
  }

我得到这样的响应,其中货币对象变为空:
 {
  currencyObject: { },
  currencyCode: "EUR",
 }

我期待这样的事情:
 {
  currencyObject: "EUR",
  currencyCode: "EUR",
 }
currency对象应转换为 JSON 字符串。而且由于我不想手动转换每个响应,我想挂入编码过程并在后台完成。

我只想为 Java.Util.Currency 添加自定义 marhaller对象,甚至 reading up on the docs我非常不确定如何继续。
描述了多种方法,我不确定哪种适合我的需要,或者从哪里开始。

我尝试创建自己的 CurrencyJsonProtocol :
package com.foo.api.marshallers

import java.util.Currency

import spray.json.{DefaultJsonProtocol, JsString, JsValue, RootJsonFormat}

object CurrencyJsonProtocol extends DefaultJsonProtocol {

  implicit object CurrencyJsonFormat extends RootJsonFormat[Currency] {
    override def read(json: JsValue): Currency = {
      Currency.getInstance(json.toString)
    }

    override def write(obj: Currency): JsValue = {
      JsString(obj.getCurrencyCode)
    }
  }

}

然而仅仅存在文件就破坏了我的项目:
[error] RouteDefinitons.scala:90:16: type mismatch;
[error]  found   : scala.collection.immutable.HashMap[String,java.io.Serializable]
[error]  required: akka.http.scaladsl.marshalling.ToResponseMarshallable
[error]       complete(shouldBeFormated)
[error]                ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed

我不知道为什么。 (由于我的包名被称为 marshaller ,它崩溃了。这完全破坏了项目的编译。

最佳答案

据我所知,你拥有所有的部分,你只需要把它们放在一起。

Spray json 提供了对常见类型的编码的支持,例如 Int、String、Boolean、List、Map 等,但是它不知道如何编码 'Currency'。为了解决这个问题,您为“货币”对象创建了一个自定义编码器。您只需要将其插入正确的位置即可。您所要做的就是从您的 CurrencyJsonProtocol 导入编码器。进入您的 Controller ,如下所示:
import CurrencyJsonProtocol._
还要确保您还有以下导入:
import spray.httpx.SprayJsonSupport._ import spray.json.DefaultJsonProtocol._
并且spray-json 应该会自动选择它。

要了解它的工作原理,您需要了解 implicits在斯卡拉。虽然当你像我一样来自 Java 世界时它看起来很神奇,但我可以向你保证它不是。

关于json - 如何将自定义编码器添加到 akka http?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771699/

相关文章:

java - JAXB - 从 Java 对象字段创建嵌套子元素

c# - .NET 值类型在内存中的布局

c# - C++ 到 C# 数组声明

java - PHP Json解析Java对象

scala - 如何使用spray RestAPI从服务器端获取http请求头信息

scala - (Some (x), None).min 和 max 的不对称性

scala - 使用默认值初始化时未绑定(bind)的占位符参数

java - 如何使用简单的 JSON 库将 json 文件读入 java

java - JsonArray 的项目没有 id

python - 无法以完全相同的格式存储或打印json数据