0

我找到了我的微服务路线。我有通用 API 可以与任何微服务通信并使用 jerkson JSON 库。

import com.codahale.jerkson.Json

case class ApiResult[T](
                         private val content: Option[String],
                         private val error: Option[Throwable]
                       ) {
  def getRaw: String = this.content.getOrElse("null")

  def get()(implicit m: Manifest[T]): T = {
       Json.parse[T](this.content.get)
  }
  def either(implicit m: Manifest[T]): Either[Throwable, T] = error match {
    case None    => Right(get)
    case Some(e) => Left(e)
  }

}

现在我有一个单例,其中包含访问另一个服务的路由的方法列表。

object PurchasesTrait extends ApiResource {

def getData(payload: String): ApiResult[ProductPurchaseResponse] = 
r[ProductPurchaseResponse](POST, Url.core + "reports/productspurchased", payload)

 }
}

我有两个案例课,

case class QualifyingProductSummary(upcCode: String, description: Option[String], purchase: Option[Double]) case class ProductPurchaseResponse(qualifyingProducts:List[QualifyingProducts], count: Int)

purchaseTrait.getData(payload) will give me the ApiResult(json, Nnone) 

json:

{"qualifyingProductSummary":[{"upcCode":"6410077902","description":"Mini-Wheats Original","purchase":15.2},{"upcCode":"6410044886","description":"Corn Pops","purchase":13.7},{"upcCode":"041570055830","description":"Unsweetened Vanilla Beverage ","purchase":13.5},{"upcCode":"626027087802","description":"Organic Almond Milk Original","purchase":12.5}],"totalQualifyingProducts":19}

val data = purchaseTrait.getData(payload).either 

当我使用任何一个时,要从 ApiResult 中获取数据,

由于QualifyingProducts,它无法在ProductPurchaseResponse中解析它。那么如何使用同一个库来实现呢?我希望通用方法也对其他嵌套的 JSON 执行相同的操作。

提前致谢。

4

0 回答 0