将JsArray的JsArray转换为Case类

时间:2019-08-15 20:56:08

标签: scala playframework jsvalue

我的问题是thisthis的一种扩展。

我的JSON如下:

{
    "id": "id1",
    "results": [
        {
            "exceed_size": "yes",
            "rows_count": 1001,
            "runtime_seconds": 0.02199999988079071,
            "columns": [
                "COL_1",
                "COL_2",
                "COL_3",
                "COL_4",
                "COL_5",
                "COL_6",
                "COL_7",
                "COL_8",
                "COL_9"
            ],
            "columns_type": [
                "number",
                "string",
                "string",
                "string",
                "number",
                "time",
                "time",
                "number",
                "string"
            ],
            "limit": 1000,
            "index": 0,
            "rows": [
                [
                    "9",
                    " C68894",
                    "                                                                                                    ",
                    "",
                    "0",
                    "2018-05-02 03:13:00.0",
                    "2017-12-02 22:32:00.0",
                    "",
                    "Approved  "
                ],
                [
                    "65",
                    "325806   ",
                    "msm                                                                             ",
                    "                 ",
                    "2",
                    "2018-05-02 03:13:00.0",
                    "2018-07-06 06:00:00.0",
                    "13",
                    "Approved  "
                ],
                ...
            ]
        },
        ...
    ]
}

我正在使用Play Framework提供的JSON库进行JSON解析。

如果您查看rows值,则它是JsArray字符串值中的JsArray。我一直在尝试将rows转换为案例类的对象列表,其中我的案例类如下:

case class Rows(col_1: String, col_2: String, ... , col_9: String)

我曾尝试做类似的事情:

val rows = (response \\ "rows").head.as[List[List[(String, String, ... , String)]]].flatten

尝试这种方式引发了一个错误,我确信这是行不通的。如何将这样的JsArray转换为案例类的对象列表?

编辑1:

按照@MilanRegmi的建议,我尝试了:

implicit val jsonFormat: Format[Rows] = Json.format[Rows]

val emails = (response \ "results" \ "rows").as[JsArray]
            .value.map(j => j.validate[Rows].get)

尝试此操作会导致:

Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List((,List(JsonValidationError(List([{"exceed_size":"yes","rows_count":1001,"runtime_seconds":0.01600000075995922,"columns":["COL_1","COL_2","COL_3","COL_4","COL_5","COL_6","COL_7","COL_8","COL_9"],"columns_type":["number","string","string","string","number","time","time","number","string"],"limit":1000,"index":0,"rows":[["9"," C68894","","","0","2018-05-02 03:13:00.0","2017-12-02 22:32:00.0","","Approved  "],["65","325806   ","msm                                                                             ","                 ","2","2018-05-02 03:13:00.0","2018-07-06 06:00:00.0","13","Approved  "],...]}] is not an object),WrappedArray())))))
    at play.api.libs.json.JsReadable$$anonfun$2.apply(JsReadable.scala:25)
    at play.api.libs.json.JsReadable$$anonfun$2.apply(JsReadable.scala:25)
    at play.api.libs.json.JsError.fold(JsResult.scala:64)
    at play.api.libs.json.JsReadable$class.as(JsReadable.scala:23)
    at play.api.libs.json.JsUndefined.as(JsLookup.scala:181)
    at com.cmdwldap.restapi.User.getEntitlementUserData(User.scala:150)
    at com.cmdwldap.restapi.User$.main(User.scala:168)
    at com.cmdwldap.restapi.User.main(User.scala)

PS:第150行对应于提到val emails的地方。

1 个答案:

答案 0 :(得分:1)

尝试一下:

val rows: Seq[Rows] = (json \ "result" \ "rows").as[JsArray].value.map(j => j.validate[Rows].get)

更新

多次询问您的问题后。我现在收到你的问题了。您要将List[List[String]转换为CaseClass

首先,您不能直接将字符串列表数组转换为案例类。因此,您需要将Array[String]转换为JsObject,其中key应该是该类的fieldName。之后,我们可以使用反射来获取fieldName。然后,我们需要使用JsObject创建caseClass来匹配List[String]fieldName

从语法上来说,上述情况可以通过以下方式解决:

 case class Rows(col1: Option[String] = None,
               col2: Option[String] = None,
               col3: Option[String] = None,
               col4: Option[String] = None,
               col5: Option[String] = None,
               col6: Option[String] = None,
               col7: Option[String] = None,
               col8: Option[String] = None,
               col9: Option[String] = None)

implicit val reads = Json.reads[Rows]

这是我们的案例类和隐式reads。现在,上面解释的部分如下:

import scala.reflect.runtime.universe._

def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect {
    case m: MethodSymbol if m.isCaseAccessor => m
  }.toList


 val rowFieldNames = classAccessors[Rows].map(k => k.name.toString)
 val results =  (json \ "results").as[JsArray].value.flatMap{
    r => (r \ "rows").as[JsArray].value
  }.map{row =>
    val rowArray = row.as[JsArray]
    val rowArraySeq = rowArray.value.map(_.as[JsString]).map(_.value)
    val map = rowArraySeq.foldLeft(Map.empty[String, JsValue]){
      (r, c) =>
        val indexOfCurrentValue = rowArraySeq.indexOf(c)
        val fieldName = rowFieldNames(indexOfCurrentValue)
        r.+((fieldName, JsString(c)))
    }
    val rowJsObject = JsObject(map)
    Json.toJson(rowJsObject)
        }.toList