简体   繁体   English

为Scup的Seq播放Scala Json作家

[英]Play Scala Json Writer for Seq of Tuple

I'm trying to find a way to use the built in Macro Json Writer in order to serialize Seq[(String,Customer)] 我正在尝试找到一种方法来使用内置的Macro Json Writer来序列化Seq [(String,Customer)]

I managed to do this for Seq[Customer] but when adding the touple, the compiler starts screaming at me. 我设法为Seq [Customer]做了这个,但是当添加touple时,编译器开始尖叫我。

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 below code (simply change from Seq[Customer] to Seq[(String,Customer)] Doesn't Copmile... Any help is really appreciated: 但是下面的代码(只需从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)
 }

}

this is the compiler error I got: 这是我得到的编译器错误:

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

The library makes no assumption as to how you want your tuple to serialize. 库不会假设您希望元组如何序列化。 You could use an array, an object, etc. 你可以使用数组,对象等。

By adding this implicit Writes function, your serializer will write it out as an array. 通过添加此隐式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)))
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM