2017-11-20 16 views
2

내가이 경우 클래스가 있다고 가정하자 : akka-http-json키르케 경우 클래스를 사용하여 기본 필드 디코딩/인코딩 JSON

를 사용하여/인코딩 API 요청/응답을 디코딩 할 때 사용된다

case class Foo(bar: String, baz: Boolean = false)

유사한 예

this에 :이 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 
      } 
     } 
     } 
    } 
    } 
} 

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 메시지에서.

+0

다음과 같습니다 추가 정보를 위해

는에서 키르케 릴리스 노트를 참조하십시오? 필요하지 않을 때는 '없음'으로 설정하십시오. –

+0

@YuvalItzchakov 좋은 제안이지만이 경우에는 [quill] (http://getquill.io/)에서도 사례 클래스를 사용합니다. 기본 필드는 데이터베이스에서'NOT NULL'이어야하기 때문에, case 클래스에서 non-option으로 유지하는 것이 좋습니다. –

답변

1

circe-generic-extras 패키지를 사용하여이를 수행 할 수 있습니다. 빌드에 넣어야하는 별도의 종속성입니다. SBT를 들어, 그건이 항상 기본 필드를 포함 생성

import io.circe.generic.extras.auto._ 
implicit val customConfig: Configuration = Configuration.default.withDefaults 

인코더 :

libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.8.0" 

그런 다음, 경로 함수와

import io.circe.generic.auto._ 

를 교체합니다. `옵션 [부울]`유효한 해결 될를 사용하여 https://github.com/circe/circe/releases/tag/v0.6.0-RC1