2017-03-22 53 views
0

我有一個Scala-Play網絡服務應用程序,它執行一些計算,生成Saddle frames並需要將這些Saddle幀轉儲到Json中。所以我定義了一個frameWrites這樣的:Scala-Play Json:如何定義任何鞍形框架的寫入?

object JsonUtils { 
    implicit def frameWrites[RX, CX, E] = new Writes[Frame[RX, CX, E]] { 
    override def writes(frame: Frame[RX, CX, E]): JsValue = { 
     val json: JsArray = Json.arr(
     (0 until frame.numRows).map { i => 
      Json.obj(
      frame.rowIx.at(i).toString -> 
       (0 until frame.numCols).map { j => 
       Json.obj(
        frame.colIx.at(j).toString -> frame.at(i, j).toString 
       ) 
       } 
     ) 
     }) 
     json 
     } 
    } 
} 

,然後嘗試使用這樣的:

import utils.JsonUtils._ 

def computingAction = Action { 
    val pnlStatistics: Frame[String, String, Double] = ??? 
    Ok(pnlStatistics) 
} 

但隨後總是錯誤Cannot write an instance of org.saddle.Frame[String,String,Double] to HTTP response. Try to define a Writeable[org.saddle.Frame[String,String,Double]]

要真正明確我自己也嘗試定義爲JsonUtils的一部分:

implicit def frameSSDWrites = frameWrites[String, String, Double] 

但是這其中也沒有得到回升...

UPDATE明確調用作家作品:

Ok(frameWrites.writes(results("PnlStatistics"))) 
+0

但是你需要實現Writeable not a Writes,對嗎? – Mysterion

回答

1

娛樂結果輸入必須有一些內容可以放在一個HTTP響應。

您的操作並不知道您要將其專門編寫爲JSON,因此您需要返回Ok(Json.toJson(pnlStatistics))

讓我們來看看這是如何工作的:

  • 類型的pnlStatisticsFrame,這樣你就可以把它序列化到JSON,使用隱式Writes[Frame],所以Json.toJson接受它作爲參數。然後它返回一個JsValue

  • 由於還存在範圍的隱式Writeable[JsValue]Ok然後接受該值作爲內容用於響應(並且也將添加Content-Type頭)。

如果您忘記了明確JSON轉換,玩也沒辦法確定要如何在響應處理的框架。

+0

非常感謝您提供詳細且有根據的答案!我檢查了它,並完美地工作。 –