我在 Play Framework 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

最佳答案

您可以在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读取以检查类型值。

关于json - Play Scala读/写,具体取决于类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27441563/

10-10 17:07