Play Scala Json Writer for Seq of Tuple

I am trying to find a way to use the built-in Json Writer macro to serialize Seq [(String, Customer)]

I managed to do this for Seq [Customer], but when the tuple is added, the compiler starts yelling at me.

This code works:

package models.health

import play.api.libs.json._

case class Customer(name: String, age: Int)

//we use the dummy var as a workaround to the json writer    limitations (cannot handle single argument case class)
case class Demo(customers: Seq[Customer], dummy: Option[String] =    None)

object Demo {

 import play.api.libs.functional.syntax._

 implicit val customer_writer = Json.writes[Customer]

 implicit val writes: Writes[Demo] = (
 (__ \ "customers").write[Seq[Customer]] and
 (__ \ "dummy").writeNullable[String]) { 
    (d: Demo) => (d.customers,d.dummy)
 }

}

      

BUT the code below (just replace Seq [Customer] with Seq [(String, Customer)] Doesn't copy ... Any help is really appreciated:

package models.health

import play.api.libs.json._

case class Customer(name: String, age: Int)

//we use the dummy var as a workaround to the json writer    limitations (cannot handle single argument case class)
case class Demo(customers: Seq[(String,Customer], dummy: Option[String] =    None)

object Demo {

 import play.api.libs.functional.syntax._

 implicit val customer_writer = Json.writes[Customer]

 implicit val writes: Writes[Demo] = (
 (__ \ "customers").write[Seq[(String,Customer)]] and
 (__ \ "dummy").writeNullable[String]) { 
    (d: Demo) => (d.customers,d.dummy)
 }

}

      

this is the compiler error i got:

No Json serializer found for type Seq[(String,models.health.Customer)]

      

+3


source to share


1 answer


The library makes no assumptions about how you want your tuple to be serialized. You can use an array, object, etc.

By adding this implicit function Writes

, your serializer will output it as an array.



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

      

+11


source







All Articles