So I have a json string which looks like this:
{
"time": 100,
"velocity": 20,
"player": [
{"name": "player1", "strength": 5},
{"name": "play2", "strength": 10}
]
}
Now I am trying to get convert the value of key "player" to a list of map in Scala. So I use:
val parsed: JsValue = Json.parse(JsString)
val players: List[Map[String, String]] = (parsed \ "player").as[List[Map[String, String]]]
And I got JsResultExceptionError and JsonValidationError .
The reason you get this error, is because you are trying to do an invalid cast. The Entry of
strengthis anint, and not aString. Therefore, you can fix that by calling:Having said that, I prefer working with case classes representing me data.
We can first define a
Player, and its format:Now we can define a class for the whole json:
And now we can parse it:
Code run at Scastie.