Search code examples
jsonscalaplayframeworkplayframework-2.0play-json

Play Framework JsReads for object names and values


Consider the following JSON:

{
  "1992": "this is dog",
  "1883": "test string",
  "1732": "unknown",
  "2954": "future year"
}

Is there any way, using JSON reads to transform this JSON into a Scala case class? i.e. a Seq[Years] or a Map[String, String], where a Year holds the year and the description.

For reference, this is how you define a read for a "simple" JSON structure:

{
  "name": "george",
  "age": 24
}

The implicit JsReads

implicit val dudeReads = (
    (__ \ "name").read[String] and
    (__ \ "age").read[Int]
) (Dude)

Solution

  • Similar to @Pranav's answer, but more concise:

    Json.parse("""
        {
          "1992": "this is dog",
          "1883": "test string",
          "1732": "unknown",
          "2954": "future year"
        }
    """).as[Map[String, String]]
    

    yields

    Map[String,String] = Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year)
    

    The underlying Reads are defined here.