は、私はこのケースクラスを考えてみましょう:akka-http-jsonキルケケースクラスで使用し、デフォルトのフィールド符号化/復号化のJSON
を使用して/エンコーディングのAPIリクエスト/レスポンスをデコードする際に使用されているcase class Foo(bar: String, baz: Boolean = false)
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"}
を送信し、結果にbaz
のFoo
のデフォルト値を使用させたいと考えています。この作業を行うことができる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メッセージで。
になります。詳細については
は、キルケのリリースノートを参照してください?必要がない場合は「None」に設定しますか? –
@YuvalItzchakovそれは良い提案ですが、このケースでは[quill](http://getquill.io/)でもcaseクラスを使用しています。デフォルトのフィールドはデータベースでは 'NOT NULL'でなければならないので、caseクラスの非オプションとして保持すると良いでしょう。 –