k0p*_*kus 11 json scala marshalling spray akka-http
作为scala和akka-http的初学者,我试图勾选序列化和编组过程.
该项目使用akka@2.5.2和akka-http@10.0.10".此外,它还包含akka-http-spray-json依赖项.
在代码库中,我们使用Java.Util.Currency(它可能已被弃用,这并不重要,因为我仍然想知道如何添加自定义编组器.)
鉴于此示例控制器:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这样的回复货币对象变空了:
{
currencyObject: { },
currencyCode: "EUR",
}
Run Code Online (Sandbox Code Playgroud)
我希望有类似的东西:
{
currencyObject: "EUR",
currencyCode: "EUR",
}
Run Code Online (Sandbox Code Playgroud)
该currency对象应转换为JSON字符串.由于我不想手动转换每个响应,我想挂钩编组过程并在后台完成.
我想仅为Java.Util.Currency对象添加自定义marhaller ,但即使阅读文档,我也不确定如何继续.描述了多种方法,我不确定哪种方法符合我的需要,或者从哪里开始.
我尝试创建自己的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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但仅仅存在该文件会破坏我的项目:
[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
Run Code Online (Sandbox Code Playgroud)
而且我不知道为什么.(由于我的包名被调用,它崩溃了marshaller.这完全破坏了项目的编译.