假设我有这个case类:
case class Foo(bar: String, baz: Boolean = false)
该类用于解码/编码API请求/响应,使用akka-http-json
类似此示例:
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
? - Yuval ItzchakovNOT NULL
,因此最好将其保留为case class中的非选项。 - simen-andresen