scala play json读取密封特征或枚举类型对象

时间:2018-10-05 15:26:33

标签: json scala playframework play-json

我有以下带有密封特征和案例对象的scala代码。

sealed trait StudentType {
  val studentLevel: String
  val code: Int
}

case object UnderGradFull extends StudentType {
  val studentLevel = "UGF"
  val code = 11
}
case object UnderGradPart extends StudentType {
  val studentLevel = "UGP"
  val code = 12
}
case object Grad extends StudentType {
  val studentLevel = "GR"
  val code = 22
}
case object OtherStudentType extends StudentType {
  val studentLevel = "OST"
  val code = 20
}

和使用StudentType

的case类对象
case class StudentInfo(studentName: String, studentType: StudentType)

object StudentInfo {
  implicit val reads: Reads[StudentInfo] = (
    (JsPath \ "studentName").read[String] and
      (JsPath \ "studentType").read[StudentType]
  )(StudentInfo.apply _)

  implicit val writes: Writes[StudentInfo] = (
    (JsPath \ "studentName").write[String] and
      (JsPath \ "studentType").write[StudentType]
  )(unlift(StudentInfo.unapply))
}

如何为implicit reads/writes创建StudentType trait

1 个答案:

答案 0 :(得分:0)

play-json似乎对密封特征具有开箱即用的支持。分析

使用它的方式似乎如下

sealed trait Family
case class ChildA(status: Boolean) extends Family
case class ChildB(name: String, age: Int) extends Family

implicit val childAFormat = Json.format[ChildA]
implicit val childBFormat = Json.format[ChildB]
implicit val familyFormat = Json.format[Family]

println(
  Json.parse(
    """{
      |  "name": "Bob",
      |  "age": 10,
      |  "_type": "controllers.ChildB"
      |}""".stripMargin
  ).as[Family]
)

将打印出ChildB(Bob,10)

play-json-extensions似乎也支持类似密封的特征

sealed trait Family
case class ChildA(status: Boolean) extends Family
case class ChildB(name: String, age: Int) extends Family

implicit val childBFormat = Jsonx.formatCaseClass[ChildB]
implicit val childAFormat = Jsonx.formatCaseClass[ChildA]
implicit val familyFormat = Jsonx.formatSealed[Family]

println(
  Json.parse(
    """{
      |  "name": "Bob",
      |  "age": 10
      |}""".stripMargin
  ).as[Family]
)

将打印出ChildB(Bob,10)

关于案例对象,我只有在它们为空时才能使它工作

sealed trait Family
case object ChildA extends Family
case object ChildB extends Family

所以我不确定如何确切地解决您的问题,但是希望这个答案能给您一些指导。