将 JsonArray 值分配给与案例类匹配的变量



我正在传递和有效载荷,这与类内的case class reportdata相似。我需要一个来获取report_data的值,这是一个选项[JSArray],

我需要将该 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")

最新更新