【问题标题】:Handle JSON data in POST request using json4s使用 json4s 处理 POST 请求中的 JSON 数据
【发布时间】:2017-03-08 06:32:37
【问题描述】:

我正在尝试将 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 来执行此操作。
任何有关这方面的帮助对我来说都很好。

【问题讨论】:

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


    【解决方案1】:

    你可以使用这个库: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))
                }
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 我添加了那个依赖 "de.heikoseeberger" %% "akka-http-circe" % "1.12.0" 。但是在导入 -> 导入 de.heikoseeberger.akkahttpjson4s.Json4sSupport 时,我得到“无法解析 akkahttpjson4s”。
    • 添加这个:"de.heikoseeberger" %% "akka-http-json4s" % "1.12.0",
    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多