2016-12-03 6 views
0

저는 현재 akka-http 문서 & 예제를 검토 중입니다. 나는 지시문 (directive)과 JsonSupport (JsonSupport)로 라우트 구성을 전달하는 등 아주 사소한 일에 아마 붙어있다. 나에 의해 정의 JsonSupportHttp().의 spray-json bindAndHandle

class RouteDef extends Directives with JsonSupport { 

:

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol { 

어떻게 내가 지금 할 수있는 나는 클래스가 akka.http.scaladsl.server.Directives를 확장 할 필요가 JsonSupport 위해 introduction에 문서 및 json-support

을 다음 해요 이 클래스를 다음에서 사용하십시오 :

val bindingFuture = Http().bindAndHandle(new RouteDef().route, "localhost", 8082) 

json 지원이 작동하지 않습니다. jsonsupport가 route val에 연결되어 있지 않습니다 (용의함).

별도의 질문 : spray-json의 상태는 어떻습니까? 스프레이가 더 이상 지원되지 않습니다. 예를 들어 스프레이 - 존슨 (Jackson)이 여전히 유지 보수되거나 교체됩니까?

+0

2 가지 특성의 코드를 공유 할 수 있습니까? 오류가 발생하고 있습니까? –

답변

1

json 지원 페이지에서 예를 시도했는데 예상대로 작동합니다.

// domain model 
final case class Item(name: String, id: Long) 
final case class Order(items: List[Item]) 

// collect your json format instances into a support trait: 
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol { 
    implicit val itemFormat = jsonFormat2(Item) 
    implicit val orderFormat = jsonFormat1(Order) // contains List[Item] 
} 

// use it wherever json (un)marshalling is needed 
class MyJsonService extends Directives with JsonSupport { 

    val route = 
    get { 
    pathSingleSlash { 
     complete(Item("thing", 42)) // will render as JSON 
    } 
    } ~ 
    post { 
     entity(as[Order]) { order => // will unmarshal JSON to Order 
     val itemsCount = order.items.size 
     val itemNames = order.items.map(_.name).mkString(", ") 
     complete(s"Ordered $itemsCount items: $itemNames") 
     } 
    } 
} 

object Main extends App { 
    implicit val system = ActorSystem("main") 
    implicit val materializer = ActorMaterializer() 

    Http().bindAndHandle(new MyJsonService().route, "localhost", 8080) 
} 

그리고 그 결과는 다음과 암시 system 또는 materializer을 정의처럼 당신이 뭔가를 놓친하지 않는 한

~❯ curl http://127.0.0.1:8080/ 
{"name":"thing","id":42}% 
~❯ curl -H "Content-Type: application/json" -X POST -d '{"items":[{"name":"thing2","id":43}]}' http://localhost:8080 
Ordered 1 items: thing2% 

그래서 그것을 작동합니다. routing-dsl overview에 따르는 것으로 설명 :

하거나 그렇지 전환도 RouteResult.route2HandlerFlow 의해 내재적으로 제공된다 Route.handlerFlow 또는 사용을 명시 적으로 호출 될 수있는 유동 행에서 전환.

이것이 문제인 경우 해당 문서도 확인해야합니다.

스프레이 - json의 경우 유지 관리 할 것인지 모르겠다. 그러나 가벼운 JSON 구현이며 현재 상당히 안정적이므로 앞으로 큰 변화가 없을 것입니다.

잭슨 마샬 러를 사용하고 싶다면 this과 같이 나만의 것을 만드는 것이 어렵지 않습니다.