gpt4 book ai didi

json - Scala Play Json 中 JsPath 到数组

转载 作者:行者123 更新时间:2023-12-02 18:15:54 28 4
gpt4 key购买 nike

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"]

关于json - Scala Play Json 中 JsPath 到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236046/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com