2

I want to convert a Cassandra table into JSON format using scala; this is the code I use to connect to Cassandra and show the table:

val cluster = Cluster.builder().addContactPoint("localhost").build()
val session = cluster.connect("MyKeySpace")
try {

  val a = session.execute("Select* from users") 
  println(a.all()) //Show as a Row-List
  //Sample --> [Row[10, Fri Jan 19 04:05:01 MST 2018, 9217], Row[10, Mon Feb 19 04:05:01 MST 2018, 9217], Row[10, Mon Mar 19 04:05:01 MDT 2018, 9217]]


  /** I have this example for the convertion but do not supports that format **/


  case class Sample (Registro: Int,Fecha: String,Valor: String )
  val agregado = Sample(999,"Wed May 20 15:19:21 MDT 31063531","982556517")
  val json= ("Reg_Num:"->agregado.Registro)~("TimeStamp:"->agregado.Fecha) ~ ("Value:"->agregado.Valor) //This is a List
  val JsonExam = println(compact(render(json)))              
  println ( pretty(render(json)) ) 
}
catch
  {
    case e: Exception => println(s"msg=${e.getMessage}")
  }

Basically, I want to convert from this format:

[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]]

To this:

{
  "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"
}
2

1 Answer 1

1

It will depend on which Json library you are using. In Play Json, we create "Writes" methods which take an instance of a case class and convert it to Json. When these are implicit then the compiler will do it "automatically" when needed. For example:

....
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"))
Sign up to request clarification or add additional context in comments.

1 Comment

Although code is almost always essential for any post including an explanation is also essential. Remember it's not only about correcting things but also telling people where they went wrong and how they can go about not doing the mistake again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.