Search code examples
jsonscalajson4s

Accessing inner JSON field in Scala


I have JSON string as

{
  "whatsNew" : {
    "oldNotificationClass" : "WhatsNewNotification",
    "notificationEvent" : { ..... },
    "result" : {
      "notificationCount" : 10
      .....
    }
  },
  ......
  "someEmpty": { },
  ......
}

I am trying to get notificationCount field using json4s in Scala as follow but notificationCount is coming as empty for all. Any help?

UPDATE Also if some pair is empty how can I handle empty condition and continue to loop?

Function returning JSON string from file

def getData(): Map[String, AnyRef] = {
  val jsonString = scala.io.Source.fromInputStream(this.getClass.getResourceAsStream("/sample.json")).getLines.mkString
  val jsonObject = parse( s""" $jsonString """)
  jsonObject.values.asInstanceOf[Map[String, AnyRef]]
}

Code to get fields

val myMap: Map[String, AnyRef] = MyDataLoader.getData

for((key, value) <- myMap) {
  val id = key
  val eventJsonStr: String = write(value.asInstanceOf[Map[String, String]] get "notificationEvent")
  val resultJsonStr: String = write(value.asInstanceOf[Map[String, String]] get "result")
  //val notificationCount: String = write(value.asInstanceOf[Map[String, Map[String, String]]] get "notificationCount")
}

Solution

  • You can use path and extract like so:

    val count: Int = (parse(jsonString) \ "whatsNew" \ "result" \ "notificationCount").extract[Int]
    

    you will need this import for the .extract[Int] to work:

    implicit val formats = DefaultFormats
    

    To do it in a loop:

    parse(jsonString).children.map { child =>
      val count: Int = (child \ "result" \ "notificationCount").extract[Int]
      ...
    }