json - 将 JsonArray 值分配给匹配案例类的变量
问题描述
我正在传递和有效载荷,它与case class reportdata
类中的 , 类似。我需要一个来获得report_data
一个 Option[JSArray] 的值,
如果该可选数组与case class reportdata
case class Fields(
reportid: Option[Long],
report_data: Option[JsArray],
header :Option[JsArray],
footer :Option[JsArray]
)
case class reportdata(
customText : Option[String],
textAlignment: Option[String],
textSize : Option[Int],
pageHeight: Long,
pageWidth: Long
)
我从数据库传递的 Json 是案例类类型字段,它有 3 个 JSON 数组。所以我想选择与报告数据的案例类匹配的json数组,我应该将它分配给一个新变量。
"reports": [
{
"reportid":513,
"report_data":[
{
"formatType": "text",
"value": "This is a sample text to be printed in the report"
},
{
"formatType": "text size",
"value": 12
},
{
"formatType": "text alignment",
"value" : "RIGHT"
},
{
"formatType": "page height",
"value" : "12"
},
{
"formatType": "page width",
"value" : "8"
}
],
"header": [
{
"formatType": "text",
"value": "Test"
},
{
"formatType": "font size",
"value": 12
}
],
"footer": [
{
"formatType": "text",
"value": "Test"
},
{
"formatType": "font size",
"value": 12
}
]
}
]
解决方案
使用第戎FTW!
这是一个测试,展示了在像您这样的样本中找到“正确”值的难易程度:
import com.github.pathikrit.dijon._
val json = parse(
"""{
|"data":[
| {
| "formatType": "text",
| "value": "bgyufcie huis huids hufhsduhfsl hd"
| },
| {
| "formatType": "text size",
| "value": 12
| },
| {
| "formatType": "text alignment",
| "value" : "right"
| }
|]
|}""".stripMargin)
assert(json.data.toSeq.collect {
case obj if obj.formatType == "text alignment" => obj.value
}.head == "right")
推荐阅读
- ios - 无法设置动态 TableView 行高
- firebase - 如何在使用 firebase/auth 和 react-native 验证他/她的电子邮件后立即登录用户而不创建整个登录页面?
- ruby-on-rails - 获取一个在 Rails / Turbo / Hotwire 中工作的简单示例时出错
- c++ - Raylib cpp IsMouseButtonPressed 导致无限循环
- javascript - Node.js 用 1 个轴对 3 个模型进行续集
- php - 如何在 laravel 中运行并行测试?
- r - 在 R/dplyr 中按条件将数据框转换为列表
- c# - 如何防止定时器停止后执行功能
- web-scraping - 如何在 Jupyter Notebook 中打印 URL 的内容?
- java - GZIPInputStream 内存泄漏