我有一个用例,我想将一个Saddle Frame序列化为Scala-Play Json。我让它适用于简单的元素类型,例如双重Frame[DateTime, String, Double]
,但现在尝试序列化其元素为复杂类型的帧类型变得有点毛茸茸。 Seq[(DateTime, Double)]
所以我有基本的frameWrites实现,适用于原始元素类型:
import play.api.libs.json._
import org.saddle._
import org.joda.time._
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 -> cellWrites(frame.at(i, j))
)
}
)
})
json
}
}}
所以我创建了一个cellWrites
来处理复杂的元素类型,如下所示:
object JsonUtils {
implicit def cellWrites[E](elem: E)(implicit tag: ClassTag[E]): JsValue = {
elem match {
case seq: Seq[(DateTime, Double)] => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this should but doesn't happen
Json.arr(
seq.map { case (dt: DateTime, value: Double) =>
Json.obj(dt.toString -> JsNumber(value))
}
)
}
case doubleValue: Double => JsNumber(doubleValue)
case _ => JsString(elem.toString)
}
}}
问题是我的Frame或类型Frame[String, String, Seq[(DateTime, Double)]]
永远不会匹配cellWrites
中相应的第一个案例。我也尝试使用隐式标记类型信息,但无法找到将其用于模式匹配的方法。这是我使用的测试用例样本:
val today = DateTime.parse("2017-11-14T13:00:00.000+01:00")
val colIx = Index("x", "y")
val data = Seq(
Series(
"a" -> Seq(
today.minusHours(2) -> 2.0,
today.minusHours(1) -> 1.0,
today.minusHours(0) -> 0.0
),
"b" -> Seq(
today.minusHours(1) -> 1.0,
today.minusHours(0) -> 0.0
)
),
Series(
"a" -> Seq(
today.minusHours(5) -> 5.0,
today.minusHours(4) -> 4.0,
today.minusHours(3) -> 3.0
),
"b" -> Seq(
today.minusHours(4) -> 4.0,
today.minusHours(3) -> 3.0
)
)
)
val frame: Frame[String, String, Seq[(DateTime, Double)]] = Frame(data, colIx)
println(frame)
请注意,上面的所有代码编译都很好。但是,按单元格类型匹配的模式不起作用。
答案 0 :(得分:0)
确定找到了,elem
实际上是org.saddle.scalar.Scalar[E]
类型,因此可行:
implicit def cellWrites[E](scalar: Scalar[E]): JsValue = {
val elem = scalar.get
elem match {
case seq: Seq[(DateTime, Double)] => {
Json.arr(
seq.map { case (dt: DateTime, value: Double) =>
Json.obj(dt.toString -> JsNumber(value))
}
)
}
case doubleValue: Double => JsNumber(doubleValue)
case _ => JsString(elem.toString)
}
}