播放2.2.2(Scala)Json解析为List [Class]问题

时间:2014-03-25 12:33:14

标签: json scala playframework

给出以下Json数组:

{
    "success": true,
    "data": [
        {
            "id": 594,
            "stage_id": 15,
            "title": "test deal",
            "value": 0,
            "currency": "EUR",
            "add_time": "2014-03-18 17:45:51",
            "update_time": "2014-03-24 13:30:27",
            "stage_change_time": "2014-03-24 13:30:27",
            "active": true,
            "deleted": false,
            "status": "open",
            "expected_close_date": null,
            "stage_order_nr": 1,
            "person_name": "test"
        },
        {
            "id": 601,
            "stage_id": 15,
            "title": "test deal2 deal",
            "value": 0,
            "currency": "EUR",
            "add_time": "2014-03-24 14:11:00",
            "update_time": "2014-03-24 14:11:00",
            "stage_change_time": "2014-03-24 14:11:00",
            "active": true,
            "deleted": false,
            "status": "open",
            "expected_close_date": null,
            "stage_order_nr": 1,
            "person_name": "test deal2"
        }
    ],
    "additional_data": {
        "pagination": {
            "start": 0,
            "limit": 100,
            "more_items_in_collection": false
        }
    }
}

我希望得到一份交易清单,我正在尝试这样做

case class Deal(id: Long, stage_id: Long)

  def getAllDeals(): List [Deal] = {

    var holder : WSRequestHolder = WS.url(PipeDriveApiBaseUrl + "/deals")

    val complexHolder: WSRequestHolder = holder.withQueryString("filter_id" -> "9", "api_token" -> SalesManagerApiKey)
    val futureResponse: Future[Response] = complexHolder.get()

    implicit val dealReader = Json.reads[List[Deal]]

    val futureJson: Future[List[Deal]] = futureResponse.map(
      response => (response.json \ "data").validate[List[Deal]].get
    )

我得到与隐式读取值相关的异常No unapply function found。但是评论一下,我会得到No Json deserializer found for type List[models.Deal]. Try to implement an implicit Reads or Format for this type.

我无法使用这些答案解决问题herehere。 我有什么想念或误解?

1 个答案:

答案 0 :(得分:4)

不是为Json.reads定义隐式List[Deal],而是为Deal创建一个:

implicit val dealReader = Json.reads[Deal]

Play已经为列表提供了内置的隐式JSON读取转换器。实际上,它适用于所有Traversables。你可以look at the code,但它有点难以阅读。问题是:Play可以将JSON列表转换为List个对象。它不知道的是如何读取/转换Deal,这就是为什么你需要上面提到的隐含定义。