json - Play JSON Reads:读取值,可以多种类型呈现
问题描述
我有这样的JSON ship
:
{
"name" : "Watership Elizbeth",
"sea": "white",
"size": 100500,
"residents" : [ {
"type" : "men",
"age" : 4,
"sex": 0
}, {
"type" : "cat",
"legs" :4,
"color" : "black",
"leg1" :{
"color" : "black"
},
"leg2" :{
"color" : "white"
},
"leg3" :{
"color" : "brown"
},
"leg4" :{
"color" : "black"
}
},{
"type" : "bird",
"size" : "XXL",
"name": "ostrich"
}, {"type": "water",...}, {"type": "mice",...}, {...}]
}
正如您在 JsArray 中看到的,residents
我有不同的居民:men
, cat
, bird
, ... water
,... 所有居民ship
在 Scala 代码中都有自己的简单案例类:
case class Men (type: String, age: Int, sex: Int)
case class Leg (color: String)
case class Cat (type: String, legs: Int, color: String, leg1: Leg, leg2: Leg, leg3: Leg, leg4: Leg)
case class Bird (...)
同样对于每个简单的案例类,我都写readers
在它们的伴随对象中:
object Men {
implicit val reads: Reads[Ship] = (
(JsPath \ "type").read[String] and
(JsPath \ "age").read[Int] and
(JsPath \ "sex").read[Int]
)(Ship.apply _)
}
// and so on for another objects...
我没有找到如何为其创建案例类的主要Ship
问题reads
:
case class Ship (name: String, sea: String, size: Int, residents: Seq[???])
object Ship {
implicit val reads: Reads[Ship] = (
(JsPath \ "name").read[String] and
(JsPath \ "sea").read[String] and
(JsPath \ "size").read[Int] and
(JsPath \ "residents").read[Seq[???]]
)(Ship.apply _)
}
如您所见residents
,数组中的元素可以是不同的类型:Men
, Cat
, Bird
.. 我想改为???
读取Ship
我的类型的所有对象或类似 `AnyVal 的对象,但它不起作用:
// for case classes
case class Ship (name: String, sea: String, size: Int, residents: Seq[Man,Cat,Bird,...])
case class Ship (name: String, sea: String, size: Int, residents: Seq[AnyVal])
// for case reads
(JsPath \ "residents").read[Seq[Man,Cat,Bird,...]]
(JsPath \ "residents").read[Seq[AnyVal]]
如何编写可以读取其关键多种类型的案例类Ship
及其?reads
解决方案
最简单的方法是从密封特征扩展所有案例类。这样 play-json 可以自动生成读取:
sealed trait Resident
case class Men (age: Int, sex: Int) extends Resident
case class Leg (color: String) extends Resident
case class Cat (legs: Int, color: String, leg1: Leg, leg2: Leg, leg3: Leg, leg4: Leg) extends Resident
case class Bird (...) extends Resident
object Resident {
private val cfg = JsonConfiguration(
discriminator = "type",
typeNaming = JsonNaming { fullName =>
fullName
.replaceFirst(".*[.]", "")
.toLowerCase
}
)
implicit val reads = Json.configured(cfg).reads[Resident]
}
case class Ship (name: String, sea: String, size: Int, residents: Seq[Resident])
object Ship {
implicit val reads: Reads[Ship] = Json.reads[Ship]
}
这是一个完整的例子。
推荐阅读
- java - Lombok 无法与 IntelliJ 2020.3 社区版一起使用
- ios - iOS 模拟器黑屏问题 Windows
- amazon-web-services - 无法从 Raspberry Pi 访问 AWS IoT Greengrass 中的 root.ca.pem 文件
- r - 如何减少ggplot中图例中的行间距
- vue.js - Nuxt - 组合 API 和观察者
- python-3.x - 线分析器与 pytest --durations
- r - 计算新事件的向量化方法
- javascript - 如何在 React 中将状态传递给道具
- python - 如何在单个包装脚本中包含和运行所有 python 脚本
- druid - Druid 搜索查询不返回区分大小写的结果