使用scala将row-List Cassandra表转换为JSON格式

时间:2018-01-25 22:17:16

标签: json scala cassandra cassandra-3.0

我想使用scala将Cassandra表转换为JSON格式;这是我用来连接Cassandra并显示表格的代码:

[Row[10, Fri Jan 19 04:05:01 MST 2018, 9217], Row[12, Mon Feb 20 04:05:01 MST 2018, 9216], Row[18, Tue Mar 21 04:05:01 MDT 2018, 9215]]

基本上,我想从这种格式转换:

{
  "Reg_Num:" : 10,
  "TimeStamp:" : "Fri Jan 19 04:05:01 MST 2018",
  "Value:" : "9217"
},
{
  "Reg_Num:" : 12,
  "TimeStamp:" : "Mon Feb 20 04:05:01 MST 2018",
  "Value:" : "9216"
},
{
  "Reg_Num:" : 18,
  "TimeStamp:" : "Tue Mar 21 04:05:01 MDT 2018",
  "Value:" : "9215"
}

对此:

{{1}}

1 个答案:

答案 0 :(得分:1)

这取决于您使用的是哪个Json库。在Play Json中,我们创建了“Writes”方法,它接受一个case类的实例并将其转换为Json。当这些是隐式的时,编译器将在需要时“自动”执行。例如:

....
import play.api.libs.json._
case class Sample(Registro: Int, Fecha: String, Valor: String ){
object Sample {
  implicit val SamplenWrites = new Writes[Sample] {
    def writes(sample: Sample):JsValue = Json.obj(
        "reg_rum"-> sample.Registro,
        "timeStamp"-> sample.Fecha,
        "value" -> sample.Valor)
      }
    }
  }

Json.obj("samples" -> Sample(5, "Fri Jan 19", "9200"))