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

时光总嘲笑我的痴心妄想 提交于 2019-12-19 08:30:14

问题


I want to convert a Seq[(String, String)] into JSON with Scala play, but I face this error:

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

How can I fix this?


回答1:


It depends on what you're trying to achieve. Say you have a Seq[(String, String)] like this:

val tuples = Seq(("z", "x"), ("v", "b"))

If you are trying to serialize it as following:

{
  "z" : "x",
  "v" : "b"
}

Then just use Json.toJson(tuples.toMap). If you'd like to have some custom representation of your tuples you can define a Writes as the compiler suggests:

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

EDIT:

import play.api.mvc._
import play.api.libs.json._

class MyController extends Controller {
  implicit val writer = new Writes[(String, String)] {
    def writes(t: (String, String)): JsValue = {
      Json.obj("something" -> t._1 + ", " + t._2)
    }
  }

  def myAction = Action { implicit request =>
    val tuples = Seq(("z", "x"), ("v", "b"))
    Ok(Json.toJson(tuples))
  }
}



回答2:


If you want to serialize Scala tuples into 2-element JSON arrays (this is pretty common), then you can write an implicit Writes object for the general case of a 2-Tuple (A, B). This will handle your case of (String, String) as well as any other combination of types!

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

If you place this in a package object, it will be visible to the entire package. That's a nice way to get consistent behavior across many classes (i.e. an entire application).



来源:https://stackoverflow.com/questions/25681091/no-json-serializer-found-for-type-seqstring-string-try-to-implement-an-imp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!