2

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

1

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._
Sign up to request clarification or add additional context in comments.

3 Comments

how to print the selected file names
Json.stringify(Json.toJson(Selection(List("x","y","z")))) @sanmoypaul
Hey @Tomer there is a little mistype in the first word of your answer.
0

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

3 Comments

The array is dynamic it comes from check box selection as a result i dnt know the filenames before hand
Please show an example how to do in this type of case
In that case you need a JsonBodyParser: playframework.com/documentation/2.5.x/JavaBodyParsers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.