Reputation:
I have a json object "{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}"
and the code:
println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content"))
result match {
case Some(e) => { println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0)
e.foreach((key: Any, value: Any) => {println(key + ":" + value)})
}
case None => println("Failed.")
}
, when I try to call map or foreach function, compiler throws an error "value foreach is not a member of Any". Can anybody suggest me a way, how i can parse this json string and convert its to Scala types
Upvotes: 4
Views: 19366
Reputation: 461
you may access keys and values in any json as:
import scala.util.parsing.json.JSON
import scala.collection.immutable.Map
val jsonMap = JSON.parseFull(response).getOrElse(0).asInstanceOf[Map[String,String]]
val innerMap = jsonMap("result").asInstanceOf[Map[String,String]]
innerMap.keys //will give keys
innerMap("anykey") //will give value for any key anykey
Upvotes: 3
Reputation: 6043
The error that you get is caused because the compiler has no way of knowing the type of e
in Some(e)
pattern, its infered as Any
. And Any
doesnt have a foreach
method. You can solve this by explicitly specifying the type of e
as a Map
.
Secondly, for a Map foreach
has the signature foreach(f: ((A, B)) ⇒ Unit): Unit
. The argument of the anonymous function is a tuple containing the key and value.
Try something like this:
println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content"))
result match {
case Some(e:Map[String,String]) => {
println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0)
e.foreach { pair =>
println(pair._1 + ":" + pair._2)
}
}
case None => println("Failed.")
}
Upvotes: 9