2
votes

I have the following Json as var dataObject ={"files": ["code.R", "data.cv", "input.txt"]}. I am posting this json as a body from the client side and I want to parse the Json and read these files names in the server side in play scala.

Please help

2

2 Answers

1
votes

Because you have only one field, you can't use json combinators, But you can do as follow:

case class Selection(files:List[String])
object Selection{
   implicit val selectionReads = (__ \ 'files).read[List[String]].map{ l => Selection(l) }
   implicit val selectionWrites = (__ \ 'files).write[List[String]].contramap { (selection: Selection) => selection.files}

   //You can replace the above 2 lines with this line - depends on you.
   implicit val selectionFormat: Format[Selection] = (__ \ 'files).format[List[String]].inmap(files => Selection(files), (selection: Selection) => selection.files)
}

Make sure you import:

import play.api.libs.functional.syntax._
0
votes

This is the documentation: https://www.playframework.com/documentation/2.5.x/ScalaJson

And the solution is simple:

import play.api.libs.json._

val json: JsValue = Json.parse("{ "files": ["code.R","data.csv","input.txt"] }")

val files = (json \ "files").get