0
我有(簡化)格式"Bar":[{"name":"Foo", "amount":"20.00"}, ...]
查找元素
我需要什麼,以便與現場amount
找到元素做等於數字的JSON(例如, 20.00
)並返回name
字段?
我有(簡化)格式"Bar":[{"name":"Foo", "amount":"20.00"}, ...]
查找元素
我需要什麼,以便與現場amount
找到元素做等於數字的JSON(例如, 20.00
)並返回name
字段?
我認爲最好的解決方案是使用案例類。我寫了這個小代碼,希望這有助於。
// define below code in models package
case class Bar(name: String, amount: Double)
implicit val barReads: Reads[Bar] = (
(JsPath \ "name").read[String] and
(JsPath \ "amount").read[Double]
) (Bar.apply _)
// define below code in Application.scala
val jsonString =
"""
[{
"name": "MyName1",
"amount": 20.0
},
{
"name": "MyName2",
"amount": 30.0
}]
"""
val jValue = Json.parse(jsonString)
val Result = jValue.validate[Seq[Bar]].fold(errors => {
println(Json.obj("status" -> "Invalid Request!!", "message" -> JsError.toJson(errors)) + "\n")
},
input => { //input will return Seq[Bar]
for (i <- input) { // looping elements in Seq
if (i.amount == 20) {
println(i.name)
}
}
})
參考:https://www.playframework.com/documentation/2.5.x/ScalaJson