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"]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다