Scala As (un)marshalling nested Seq collections with Spray JSON

Scala Akka (un)marshalling nested Seq collections with Spray JSON

我正在尝试使用 Spray JSON 将下面的 'Seq' 集合编组到具有定义参数的 'BidRequest' 实体中。 Seq 集合大多是嵌套的,因此一些 'Seq' 参数字段也有需要编组的变量集合类型。 然后在计算之后,目的是将结果解组为 'BidResponse'.

的实体

执行此操作的最佳方法是什么?

我正在使用 Akka-HTTP、Akka-Streams、Akka-Actor。

序列集合:


      val activeUsers = Seq(
          Campaign(
              id = 1,
              country = "UK",
              targeting = Targeting(
                  targetedSiteIds = Seq("0006a522ce0f4bbbbaa6b3c38cafaa0f") 
                  ),
                  banners = List(
                      Banner(
                          id = 1,
                          src ="https://business.URLTV.com/wp-content/uploads/2020/06/openGraph.jpeg",
                          width = 300,
                          height = 250
                          )
                        ),
                  bid = 5d
                )
            )

BidRequest 案例class:

case class BidRequest(id: String, imp: Option[List[Impression]], site:Site, user: Option[User], device: Option[Device])

BidResponse 案例 class:

case class BidResponse(id: String, bidRequestId: String, price: Double, adid:Option[String], banner: Option[Banner])

另一种情况class是:


case class Campaign(id: Int, country: String, targeting: Targeting, banners: List[Banner], bid: Double)
case class Targeting(targetedSiteIds: Seq[String])
case class Banner(id: Int, src: String, width: Int, height: Int)

case class Impression(id: String, wmin: Option[Int], wmax: Option[Int], w: Option[Int], hmin: Option[Int], hmax: Option[Int], h: Option[Int], bidFloor: Option[Double])
case class Site(id: Int, domain: String)
case class User(id: String, geo: Option[Geo])
case class Device(id: String, geo: Option[Geo])
case class Geo(country: Option[String])

到目前为止,我已经尝试使用下面的代码,但一直收到类型不匹配错误:

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

implicit val resFormat = jsonFormat2(BidResponse)
implicit val bidFormat = jsonFormat1(BidRequest)
implicit val cFormat = jsonFormat1(Campaign)
implicit val tFormat = jsonFormat1(Targeting)
implicit val bFormat = jsonFormat1(Banner)
implicit val iFormat = jsonFormat1(Impression)
implicit val sFormat = jsonFormat1(Site)
implicit val uFormat = jsonFormat1(User)
implicit val dFormat = jsonFormat1(Device)
implicit val gFormat = jsonFormat1(Geo)

Spray JSON 出现类型错误的原因是因为您需要使用相应的 jsonFormatN 方法,具体取决于案例中的参数数量class.

你的情况:

implicit val resFormat = jsonFormat5(BidResponse)
implicit val bidFormat = jsonFormat5(BidRequest)
implicit val cFormat = jsonFormat1(Campaign)
implicit val tFormat = jsonFormat1(Targeting)
implicit val bFormat = jsonFormat4(Banner)
...