gpt4 book ai didi

json - 根据类型 Play Scala 读/写

转载 作者:行者123 更新时间:2023-12-04 21:14:29 25 4
gpt4 key购买 nike

根据类字段,我无法在 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] )。我还添加了 verifying如果同时 Price,则读取以检查类型值和 Weight碰巧有相同的结构。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com