根据类型播放Scala读/写

时间:2014-12-12 10:25:12

标签: json scala playframework

我在播放框架2.3中处理Json阅读器时遇到了麻烦,具体取决于类字段:

我的模特:

trait Data{
  val id:String
  val type:String
  val creation_date:Date
}

case class Price(
  id:String,
  type:String,
  creation_date:Date,
  amount:Int,
  currency:String) extends Data

case class Weight(
  id:String,
  type:String,
  creation_date:Date,
  value:Int,
  unit_of_measurement:String) extends Data

case class MyObject(
  id:String,
  data:List[Data]
)

我的问题是: 我如何阅读MyObject类并保留Json的所有值,如:

{
  id:"1",data:
    [
      {
        id:"1",
        type:"price",
        creation_date:"2014-12-01T00:00:00.000Z",
        amount:99,
        currency:"dollar"
      },
      {
        id:"1",
        type:"price",
        creation_date:"2014-12-01T00:00:00.000Z",
        amount:99,
        currency:"dollar"
      },
      {
        id:"1",
        type:"weight",
        creation_date:"2014-12-01T00:00:00.000Z",
        value:2,
        unit_of_measurement:"tonne"
      }
    ]
}

我试过了:

implicit val myObjectReads: Reads[MyObject] = (
  ....
  (__ \ "data").read(Reads.traversableReads[List,Data])

但它不起作用

非常感谢你的帮助!

MC

1 个答案:

答案 0 :(得分:2)

您可以使用orElse特征中的Reads方法:

import play.api.libs.json.Reads.verifying

val priceReads: Reads[Price] = verifying[Price](_.`type` == "price")(Json.reads[Price])
val weightReads: Reads[Weight] = verifying[Weight](_.`type` == "weight")(Json.reads[Weight])
implicit val dataReads: Reads[Data] = priceReads.map(identity[Data]) orElse weightReads.map(identity[Data])
implicit val myObjectReads: Reads[MyObject] = Json.reads[MyObject]

请注意,在使用Reads[Price]之前,我需要将Reads[Weight]Reads[Data]映射到orElse,因为Reads不是协变的(Reads[Price]不是Reads[Data])。如果verifyingPrice碰巧具有相同的结构,我还添加了Weight次读取以检查类型值。