scala - 在 Play Framework 中运行时构建读取转换器和案例类
问题描述
我有一个包含以下 JSON 对象数组的文件:
[
{
"type": "home",
"number": 1111
},
{
"type": "office",
"number": 2222
},
{
"type": "mobile",
"number": 3333
}
]
在 Play Framework 2.x 中,我将定义一个隐式读取转换器来读取文件并将其转换为 Scala 结构:
implicit val implicitRead : Reads[MyClass] = (
(JsPath \ "type").read[String] and
(JsPath \ "number").read[Int]
) (MyClass.apply _)
Scala案例类定义为:
case class MyClass (myType: String, myNumber: Int)
并解析 JSON:
val json = // file record content
json.validate[MyClass] match {
case s: JsSuccess[MyClass] => {
val myObject: MyClass = s.get
// do something with myObject
}
case e: JsError => {
// error handling flow
}
现在,我的问题是我只知道 JSON 文件的结构runtime
,而不是compilation time
。是否可以同时构建隐式读取转换器和案例类runtime
?
解决方案
case classes
直接使用play-json
:
更改case class
为:
case class MyClass (`type`: String, number: Int)
添加json-formatter
到伴随对象:
object MyClass {
implicit val format = Json.format[MyClass]
}
该validate
函数现在看起来:
val myClass = // file record content
json.validate[Seq[MyClass]] match {
case JsSuccess(myClasses, _) => myClasses
case e: JsError => // handle error case
}
这就是你所需要的。如果您对参数名称不满意,可以使用 Wrapper 案例类。
推荐阅读
- tensorflow - 如何在 Conv2d 中指定依赖于样本的内核/过滤器?
- unity3d - 场景的 GameObjects 轻微出血问题
- python - 如何从python中的条件列表中选择一个随机单词
- node.js - Flutter JSON数据问题
- javascript - 使用 promise() 运行下一个函数不起作用 - PLAIN JAVASCRIPT
- python - Python 中的 scanf() 生产问题
- visual-studio - 在我所有的浏览器中 Windows 10 更新 2004 后奇怪的本地主机证书问题!我怎样才能解决这个问题?
- linux - 在 WSL 2 上使用 Ansible 通过 snap 安装 microk8s
- angular - 在 Ionic 5 中使用 Capacitor 实现 Google Analytics
- leaflet - 将一个多边形的数据复制粘贴到另一个,LEAFLET