使用自定义转换器函数播放 Json 个案例 class 个映射器

Play Json case class mapper with custom converter function

我有一个 json 看起来像这样。

{
"key1": "val1",
"key2": "val2",
//other stuff
"key5": {
  "nkey1": [
    "nval1",
    "nval2"
  ],
  "nkey2": 90,
  "nkey3": 100
},
"page": 1,
"rows": 30,
"result_count": 3,
"parser_result": null,
"ip_address": "10.0.0.1",
"search_date": "20151013 05:12:05",
"key6": [
  //more key values
]
}

我需要一个对象映射器来使用 scala case classes 使用 play 框架。我可以为简单的 classes 编写转换。但是,我有一些在 getMap class 中给出的自定义功能,它采用 JsPath \ "key5" 中的 jObject 实例,如下面的代码所示。我该如何实现它,因为我的方法似乎无法实现它。

implicit val myReads: Reads[MyCustomObject] = (
  (JsPath \ "key1").read[String] and
    (JsPath).read[CustomObject] and
    (JsPath \ "key3").read[String] and
    (JsPath \ "key4").readNullable[String] and
    (JsPath \ "key5").read(/*How do I call getMap here*/) and
    (JsPath \ "key6").read[Seq[CustomObject2]]
  )(SearchQuery.apply _)

def getMap(jsObject: JsObject):Map[String, List[JsValue]] ={
  val r = Map[String, List[JsValue]]() ++ jsObject.fields.map(keyValues => {
    keyValues._2 match {
      case JsArray(arr) => keyValues._1 -> arr.toList
      case v: JsValue => keyValues._1 -> List(v)
      case _ => keyValues._1 -> List()
    }
  })
  r
}

我使用以下代码片段解决了我的问题。基本上这只是另一个可以使用常规 Scala 语法修改的构造函数。

implicit val myReads: Reads[MyCustomObject] = (
  (JsPath \ "key1").read[String] and
  (JsPath).read[CustomObject] and
  (JsPath \ "key3").read[String] and
  (JsPath \ "key4").readNullable[String] and
  (JsPath \ "key5").read(JsValue) and
  (JsPath \ "key6").read[Seq[CustomObject2]]
)(key1: String, custom: CustomObject, key3: String, key4: Option[String,
  key5: JsValue, key6: Seq[CustomObject2){
  SearchQuery.apply(key1, custom, key3, key4, transformToMap(key5), key6) // Where transformToMap is a custom function that I have defined.
}