使用json4s处理POST请求中的JSON数据

时间:2017-03-08 06:32:37

标签: json scala akka-http case-class json4s

我试图将JSON i / p映射到我的案例类CacheRequest 请求是POST。
我是Scala和Akka的新人。

import org.json4s.{DefaultFormats, Formats}
implicit val formats: Formats = DefaultFormats
val route: Route = traceContextAwareRoute {
            pathPrefix(system.name) {
              post {
                path("sample") {
                  entity(as[CacheRequest]) { x => {
                    val cacheRequest: CacheRequest = CacheRequest(x.a, x.b, x.c, x.d, x.e, x.f)

                    onComplete(getSystemStock(cacheRequest)) {
                      (response: Try[Option[CacheResponse]]) => complete(processResponse(response))
                    }
                  }

                  }
                }
              }
            }


我的案例类是这样的。

case class CacheRequest(a: String,
                        b: String,
                        c: Int,
                        d: Int,
                        e: Int,
                        f: Int)

获得错误

could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[mcc.movie.common.model.CacheRequest]

not enough arguments for method as: (implicit um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[mcc.movie.common.model.CacheRequest])akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[mcc.movie.common.model.CacheRequest]

我应该使用json4s来做这件事 对此我有任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用此lib:https://github.com/hseeberger/akka-http-json

代码可能是这样的

import org.json4s.{DefaultFormats, Formats, jackson}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport

class Route {
  import Json4sSupport._
  implicit val formats: Formats = DefaultFormats
  implicit val serialization = jackson.Serialization

  val route: Route = traceContextAwareRoute {
    pathPrefix(system.name) {
      post {
        path("sample") {
          entity(as[CacheRequest]) { x => {
            val cacheRequest: CacheRequest = CacheRequest(x.a, x.b, x.c, x.d, x.e, x.f)

            onComplete(getSystemStock(cacheRequest)) {
              (response: Try[Option[CacheResponse]]) => complete(processResponse(response))
            }
          }
        }
      }
    }
  }
}