json - 为元组序列 Play Scala Json Writer

标签 json scala playframework

我正在尝试找到一种方法来使用内置的 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/

相关文章:

scala - 覆盖 toString 时如何使用条件语句

python - 基于 Spark Dataframe 中不同值的类别列

scala - Play 2.3 cookie 在过期后仍然可用

java - 使用 Jackson 将 Json 映射到 Java POJO

java - jackson JsonMappingException : Can not deserialize instance

javascript - 动态填充谷歌柱形图

javascript - 检索 JSON 数据未按预期工作

Scala:扩展内部类,不引用外部类

Java、泛型和 Classe<Generic> 问题

java - 玩2.3.x : Non-blocking image upload to Amazon S3