在子类中重用json隐式读者

时间:2015-12-08 12:13:23

标签: json scala playframework

想象一下以下场景:

我有两个类,一个扩展另一个。我想定义隐式读取以从json转换为类。 看一下这个例子:

case class A(field1: String, field2: Int)

object A {
  implicit val reads: Reads[A] = (
    (__ \'field1).read[String] and
    (__ \'field2).read[Int]
  )(A.apply _)
}

case class B(field1: String, field2: Int, field3: Boolean)

object B {
  implicit val reads: Reads[B] = (
    (__ \'field1).read[String] and
    (__ \'field2).read[Int] and
    (__ \'field3).read[Boolean]
  )(B.apply _)
}

我的问题是如何避免隐式读取中的代码重复。 如果B类扩展A,那么Reads [B]如何重用Read [A]并避免读者中的代码重复? 我知道在这种情况下,B类不会扩展A,因为它们被定义为案例类。我可以将它们的定义更改为普通类,甚至可以根据需要定义特征。

我需要以 B是A

的方式保持班级之间的关系

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试像:

import play.api.libs.json._
import play.api.libs.functional.syntax._

object A {
  val readsFields = (__ \'field1).read[String] and (__ \'field2).read[Int]
  implicit val reads: Reads[A] = (
    aReadsFields
  )(A.apply _)
}

object B {
  implicit val reads: Reads[B] = (
    A.readsFields and
    (__ \'field3).read[Boolean]
  )(B.apply _)
}

或者,您可以定义类之间的关系:

case class A(field1: String, field2: Int)

object A {
  implicit val reads: Reads[A] = (
    (__ \'field1).read[String] and
    (__ \'field2).read[Int]
  )(A.apply _)
}

case class B(field1: A, field3: Boolean)

object B {
  implicit val reads: Reads[B] = (
    (__ \'field1).read[A] and
    (__ \'field3).read[Boolean]
  )(B.apply _)
}

查看播放框架教程以获取详细信息: https://www.playframework.com/documentation/2.4.x/ScalaJson