2015-10-14 65 views
0

我有一個看起來像這樣的json。與自定義轉換器功能發揮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類的對象映射器使用play框架。我可以爲簡單的類編寫轉換。不過,我有一些自定義功能,它是在getMap類中給出的,它在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 
} 

回答

0

我用下面的代碼解決了我的問題。基本上這只是另一個可以使用常規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. 
} 
相關問題