Reputation: 209
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
Upvotes: 2
Views: 1369
Reputation: 2448
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._
Upvotes: 1
Reputation: 1097
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
Upvotes: 0