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

后端 未结 2 1476
终归单人心
终归单人心 2021-01-13 23:56

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[(Strin

2条回答
  •  无人及你
    2021-01-14 00:36

    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).

提交回复
热议问题