2016-09-05 137 views
0

我有(简化)格式"Bar":[{"name":"Foo", "amount":"20.00"}, ...]查找元素

我需要什么,以便与现场amount找到元素做等于数字的JSON(例如, 20.00)并返回name字段?

回答

0

我认为最好的解决方案是使用案例类。我写了这个小代码,希望这有助于。

// 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