【问题标题】:Play Scala Json Writer for Seq of Tuple为元组序列播放 Scala Json Writer
【发布时间】:2015-06-18 17:21:23
【问题描述】:

我正在尝试找到一种方法来使用内置的 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)] 不兼容...任何帮助非常感谢:

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

【问题讨论】:

    标签: json scala playframework


    【解决方案1】:

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

    通过添加这个隐含的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)))
      }
    

    【讨论】:

    • 如果你升级到 Play 2.6.1,你就不必再这样做了——他们有这个用例的默认序列化。
    猜你喜欢
    • 2016-07-26
    • 1970-01-01
    • 2015-02-28
    • 2021-03-07
    • 2013-07-28
    • 1970-01-01
    • 2013-07-11
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多