我选择了微服务。我有通用的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)
}
}
我有两个案例类,
案例类QualifyingProductSummary(upcCode:字符串,描述:Option [String],购买:Option [Double]) 案例类ProductPurchaseResponse(qualifyingProducts:List [QualifyingProducts],计数: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时从ApiResult中获取数据,
由于合格产品,它无法在 ProductPurchaseResponse 中进行解析。那么如何使用相同的库来实现呢? 我希望通用方法也可以对其他嵌套JSON执行相同的操作。
谢谢。