[英]JsPath to array in Scala Play Json
import play.api.libs.json._
val json: JsValue = Json.parse("""
{
"name" : "Independence",
"foundingFathers" : [ {
"name" : {
"first": "John",
"last": "Adams"
},
"country" : "United States"
}, {
"name" : {
"first": "Artur",
"last": "Mas"
},
"country" : "Catalonia"
} ]
}
""")
val lastNames = json \ "foundingFathers \ "name" \ "last"
// this does not work. it fails with: JsUndefined('last' is undefined on object: JsUndefined('name' is undefined on object: [{"name":{"first":"John","last":"Adams"},"country":"United States"},{"name":{"first":"Artur","last":"Mas"},"country":"Catalonia"}]))
// this does work, but there is too much boilerplate
val lastNames = (json \ "foundingFathers").as[List[JsObject]].map(_ \ "name" \ "last")
沒有樣板怎么實現結果? (在這種情況下,我想使用JsValues,我不想使用閱讀器將JsValue轉換為模型)
您可以使用隱式類將此功能包裝起來
implicit class JsValueWrapper(val j: JsValue) extends AnyVal {
def \|(fieldName: String) = j match {
case JsArray(value) => JsArray(value.map(_ \ fieldName))
case _ => j \ fieldName
}
}
scala> json \| "foundingFathers" \| "name" \| "first"
res19: play.api.libs.json.JsValue = ["John","Artur"]
小改進,不確定是否能回答您的問題
val lastNames = json \ "foundingFathers" \\ "name" map ( _ \ "last")
lastNames:Seq [play.api.libs.json.JsValue] = ListBuffer(“ Adams”,“ Mas”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.