首页 > 解决方案 > 将 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
                }
            ]
        }
    ]

标签: jsonscalacase-class

解决方案


使用第戎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")

推荐阅读