Pergunta

i am developing app using play framework in scala i want response in json but how to do that compile time error is coming

 No Json deserializer found for type List[(String, String)]. Try to implement an implicit Writes or Format for this type.

List buffer is

ListBuffer((This,a choke), (a Cv,15.6 gal))

i also did this

Json.toJson(list))

but still getting error.

any one give me some idea to solve this issue.

Foi útil?

Solução

What json representation of (String, String) do you expect it to be? If it is something like this:

yourListName : {
  "1" : "2",
  "3" : "4"
}

then you could just use Json.toJson(list.toMap). Otherwise, you must define a Writes for a (String, String) like this:

implicit val writer = new Writes[(String, String)] {
    def writes(c: (String, String)): JsValue = {
      Json.obj("something" -> c._1 + ", " + c._2)
      //or like this:
      //Json.obj(c._1 -> c._2)
    }
  }

Be sure to have this writer in scope

Outras dicas

As discussed in this thread [2.1] Json.format macros and Tuple2 play-json 2.1 doesn't support tuples yet mainly because json doesn't support tuples. If you want your tuples to be writtern as an array you might use implicit format for tuples:

implicit def tuple2Writes[A, B](implicit aWrites: Writes[A], bWrites: Writes[B]): Writes[Tuple2[A, B]] = new Writes[Tuple2[A, B]] {
  def writes(tuple: Tuple2[A, B]) = JsArray(Seq(aWrites.writes(tuple._1), bWrites.writes(tuple._2)))
}

You can do this in a line, simply declare this implicit:

implicit def tuple2[A : Writes, B : Writes] = Writes[(A, B)] ( t =>  Json.obj("something1" -> t._1, "something1" -> t._2) )
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top