Scala将对象转换为JSON响应

时间:2019-05-20 10:39:54

标签: scala akka akka-http spray-json

如何将以下案例类对象转换为JSON响应,该案例类包含多个嵌套对象值。

使用jsonFormat5(responseData)

时出现异常
val simpleBanner1 = Banner(112, "http://dummyimage.com/300x250", 300, 250)
val responseData = BidResponse(uuid, "XN2zZQABxJsKK0jU4QnIzw", campaignData.bid, Option("4548"), Option(simpleBanner1))

异常

Error:(63, 47) could not find implicit value for evidence parameter of type bidder.RestService.JF[Option[bidder.Banner]]
implicit val bidResponseFormat = jsonFormat5(BidResponse)

Error:(63, 47) not enough arguments for method jsonFormat5: (implicit evidence$25: bidder.RestService.JF[String], implicit evidence$26: bidder.RestService.JF[String], implicit evidence$27: bidder.RestService.JF[Double], implicit evidence$28: bidder.RestService.JF[Option[String]], implicit evidence$29: bidder.RestService.JF[Option[bidder.Banner]], implicit evidence$30: scala.reflect.ClassTag[bidder.BidResponse])spray.json.RootJsonFormat[bidder.BidResponse].
Unspecified value parameters evidence$29, evidence$30.
implicit val bidResponseFormat = jsonFormat5(BidResponse)

Error:(76, 28) Cannot find JsonWriter or JsonFormat type class for bidder.BidResponse
          responseData.toJson
Error:(76, 28) not enough arguments for method toJson: (implicit writer: spray.json.JsonWriter[bidder.BidResponse])spray.json.JsValue.
Unspecified value parameter writer.
          responseData.toJson

1 个答案:

答案 0 :(得分:1)

jsonFormat5应该与case类一起使用,因为它定义了对象的编码方式。您的代码应如下所示:

import spray.json._
import DefaultJsonProtocol._

// define format implicitly for BidResponse and Banner case classes
implicit val bannerFormat = jsonFormat4(Banner)
implicit val bidResponseFormat = jsonFormat5(BidResponse)

// serialize BidResponse object
val bidResponseJson = responseData.toJson

这是一个扩展的示例:

import spray.json._
import DefaultJsonProtocol._

// example case classes
case class Banner(num: Int, url: String, num2: Int, num3: Int)
case class BidResponse(uuid: String, code: String, num: Int, opt: Option[String], banner: Option[Banner])

implicit val bformat = jsonFormat4(Banner)
implicit val format = jsonFormat5(BidResponse)

val simpleBanner1 = Banner(112, "http://dummyimage.com/300x250", 300, 250)
val responseData = BidResponse("abcdef", "XN2zZQABxJsKK0jU4QnIzw", 1234, Option("4548"), Option(simpleBanner1))

println( responseData.toJson )

如注释中所述,必须隐式定义Banner格式,因为BidResponse对象依赖于它。 ref:bformat变量。