为Scup的Seq播放Scala Json作家

时间:2015-06-18 17:21:24

标签: json scala playframework

我试图找到一种方法来使用内置的Macro Json Writer来序列化Seq [(String,Customer)]

我设法为Seq [Customer]做了这个,但是当添加touple时,编译器开始尖叫我。

此代码有效:

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

1 个答案:

答案 0 :(得分:12)

库不会假设您希望元组如何序列化。您可以使用数组,对象等。

通过添加此隐式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)))
  }