Search code examples
jsonscalahttpplayframeworkrest

How to parse a Json with days received from HTTP request into a list in Scala and Play Framework


I'm new to Scala and Play Framework. I have a Json like this:

{
   "monday" : [],
   "tuesday" : [
       {
          "type" : "xyz",
          "value" : 1111
       },
       {
          "type" : "abc",
          "value" : 2222
       }
   ],
   .....
}

I'm trying to reading this Json in a list, or map, that contain, for every entry, a list of type/value. I've defined a method that read the HTTP request body

def readJson() = Action { implicit request =>
      val body = request.body
      val jsonObject = body.asJson
}

I don't understand though how to continue, I've read the Play Framework documentation but I'm a bit lost. Anyone can help? Thanks!


Solution

  • You can follow this

    import play.api.libs.json._
    
    final case class Task(
        `type`: String,
        value: Int
    )
    final case class Days(
        monday: List[Task],
        tuesday: List[Task]
    )
    
    
    implicit val ts = Json.format[Task]
    implicit val da = Json.format[Days]
    
    
    def readJson() = Action { implicit request =>
          
          val days:Option[Days] = request.body.asJson.getOrElse(Json.obj()).asOpt[Days]
      // .....
    }
    

    or instead of mapping json to Case class, you can use jsPath see https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators