0

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 .

1

1 Answer 1

1

The reason you get this error, is because you are trying to do an invalid cast. The Entry of strength is an int, and not a String. Therefore, you can fix that by calling:

val players: List[Map[String, String]] = (parsed \ "player").as[List[Map[String, Any]]]

Having said that, I prefer working with case classes representing me data.

We can first define a Player, and its format:

case class Player(name: String, strength: Int)

object Player {
  implicit val format: OFormat[Player] = Json.format[Player]
}

Now we can define a class for the whole json:

case class Entity(time: Int, velocity: Int, player: Seq[Player])

object Entity {
  implicit val format: OFormat[Entity] = Json.format[Entity]
}

And now we can parse it:

val json = Json.parse(jsonString)
json.validate[Entity] match {
  case JsSuccess(entity, _) =>
    println(entity)
  case JsError(_) => ???
}

Code run at Scastie.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.