【发布时间】:2018-05-03 11:11:00
【问题描述】:
假设我有这个案例类:
case class Foo(bar: String, baz: Boolean = false)
在使用akka-http-json对API请求/响应进行解码/编码时使用
在类似于this的示例中:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.{ ActorMaterializer, Materializer }
import scala.io.StdIn
object ExampleApp {
private final case class Foo(bar: String, baz: Boolean = false)
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
Http().bindAndHandle(route, "127.0.0.1", 8000)
StdIn.readLine("Hit ENTER to exit")
system.terminate()
}
private def route(implicit mat: Materializer) = {
import Directives._
import FailFastCirceSupport._
import io.circe.generic.auto._
pathSingleSlash {
post {
entity(as[Foo]) { foo =>
complete {
foo
}
}
}
}
}
}
只要 json 消息包含 baz 字段,它就可以正常工作。但是,我希望能够发送 json 消息{bar: "something"},并让结果使用Foo 的默认值baz。 circe 或 akka-http-json 中是否有任何配置可以完成这项工作?
另外,在再次编码为 json 时忽略 baz 字段会很好,但这并不重要。
编辑:
我知道我可以这样做:
implicit val fooEncoder: Encoder[Foo] = new Encoder[Foo] {
final def apply(a: Foo): Json = Json.obj(
("id", Json.fromString(a.bar))
)
}
implicit val fooDecoder: Decoder[Foo] = new Decoder[Decoder] {
final def apply(c: HCursor): Decoder.Result[Decoder] =
for {
bar <- c.downField("bar").as[String]
} yield {
Foo(bar)
}
}
但希望有一个更易于维护的解决方案,解决不需要 json 消息中的默认字段的一般情况。
【问题讨论】:
-
使用
Option[Boolean]是一种有效的解决方法吗?并在不需要时将其设置为None? -
@YuvalItzchakov 这是一个很好的建议,但在这种情况下,我们也将 case 类与quill 一起使用。由于我们数据库中的默认字段应为
NOT NULL,因此最好将其保留为案例类中的非选项。 -
@simen-andresen 您应该考虑接受以下解决方案