1
votes

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)
2

2 Answers

4
votes

Convert your json string to JsValue and then use validate on the JsValue object.

scala> val json: JsValue = Json.parse("""
 | {
 |   "1992": "this is dog",
 |   "1883": "test string",
 |   "1732": "unknown",
 |   "2954": "future year"
 | }
 | """)
json: play.api.libs.json.JsValue = {"1992":"this is dog","1883":"test string","1732":"unknown","2954":"future year"}

scala> val valid = json.validate[Map[String,String]]
valid: play.api.libs.json.JsResult[Map[String,String]] = JsSuccess(Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year),)

scala> valid match {
 | case s: JsSuccess[Map[String,String]] => println(s.get)
 | case e: JsError => println("Errors: " + JsError.toJson(e).toString())
 | }
Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year)
3
votes

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.