我有以下 json
"atrr": {
"data": {
"id": "asfasfsaf",
"name": "cal",
"type": "state"
"ref": [
"xyz",
"uhz",
"arz"
]
}
}
我正在閱讀以下內容,但沒有獲得價值 k,v
def getData: Map[String, String] = (atrr \ "data").asOpt[Map[String, String]].getOrElse(Map[String, String]())
沒有ref它作業正常。如何在作為物件的代碼中忽略來自 json 的 ref[]
uj5u.com熱心網友回復:
您可以使用自定義Reads[Map[String, String]],傳遞給.asor.asOpt方法。我的方法是使用Reads.optionNoError[String]來處理主atrr物件內的值,這樣任何會導致錯誤的非字串欄位都將被視為None.
// explicitly construct something that'd normally be constructed implicitly
val customReads: Reads[Map[String, Option[String]] =
Reads.map(Reads.optionNoError[String])
// pass the custom reads explicitly with parens,
// instead of passing the expect type in square brackets
(atrr \ "data").asOpt(customReads)
這導致
Some(
Map(
id -> Some(asfasfsaf),
name -> Some(cal),
type -> Some(state),
ref -> None
)
)
你可以改變你認為合適的方式,例如通過做
.map(_.collect { case (k, Some(v)) => k -> v })
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404555.html
標籤:
下一篇:反向字典屬性設定為ids?
