我正在尝试找到一种方法来使用内置的 Macro Json Writer 来序列化 Seq[(String,Customer)]
我成功地为 Seq[Customer] 做到了这一点,但是当添加元组时,编译器开始对我尖叫。
此代码有效:
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)
}
}
但是下面的代码(只需从 Seq[Customer] 更改为 Seq[(String,Customer)] 不会 Copmile...非常感谢任何帮助:
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)
}
}
这是我得到的编译器错误:
No Json serializer found for type Seq[(String,models.health.Customer)]
最佳答案
该库不会假设您希望元组如何序列化。您可以使用数组、对象等。
通过添加此隐式 Writes
函数,您的序列化程序会将其写为数组。
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)))
}
关于json - 为元组序列 Play Scala Json Writer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30921821/