简体   繁体   中英

How to parse a json string to a List of Map in scala?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM