Reputation: 5619
in my play Framework app I send an json to backend, in backend I want to access on array in the json
I tried this:
val processSteps = request.body.asJson.map{
json => (json \ "stepsData").asOpt[Object].map { steps =>
println(steps)
}
for (processStep <- steps) {
processStep.map(_.validate[ProcessStepTemplatesModel] match {
stepsData is an array I want to access
Request:
Some({"steps":"","stepsData":[{"steptitle":"sd","title":"asd"}],"stepType":"duty","createdat":"2017-05-31 14:30:26","updatedat":"2017-05-31 14:30:26","activeSnackbar":false,"snackbarText":{"type":"span","key":null,"ref":null,"props":{"children":[{"key":null,"re
f":null,"props":{"value":"snackbar.processes.createProcess"},"_owner":null,"_store":{}},": ",null]},"_owner":null,"_store":{}},"approvedProcessTemplates":[],"approveprocess":17,"approveprocessTitle":"Felix","trainingsprocess":47,"trainprocessTitle":"Posaune","d
eleted":false,"dialogActive":false,"title":"ads","processtemplate":1,"loaded":true,"version":"asd","responsible":"asd","accountable":"asd","consulted":"asd","informed":"asd","deadline":"2017-05-18T12:30:09.460Z","dialogActions":[{"label":{"key":null,"ref":null,
"props":{"value":"dialog.processes.deleteProcess.cancel"},"_owner":null,"_store":{}}}],"dialogTitle":{"key":null,"ref":null,"props":{"value":"dialog.processes.selectProcessTemplate.trainingsprocess.header"},"_owner":null,"_store":{}},"dialogHandlerVariable":1})
Upvotes: 1
Views: 935
Reputation: 5315
You should do this in json validation, that is in your asOpt
method:
(json \ "stepsData").asOpt[Array[ProcessStepTemplatesModel]]
If you're using other fields in the body, you could even define a case class for expected body, and validate it directly:
case class StepProcessingRequestData(
stepsData: Array[ProcessStempTemplatesModel],
... // add your other fields, as defined in your JSON schema
)
object StepProcessingRequestData {
implicit val reads = Json.reads[StepProcessingRequestData]
}
val processStepsOpt: Option[StepProcessingRequestData] =
request.body.asJson.flatMap(_.asOpt[StepProcessingRequestData])
Upvotes: 1
Reputation: 737
Can you show me how your data looks like?
The way I would approach this is, have a case class for stepsData :
case class StepData(attributes ..)
And then have a wrapper :
case class StepDataWrapper(stepsData : List[StepData])
Then specify an implicit format in your controller :
import play.api.libs.json._
implicit val stepDataFormat = Json.format[StepData]
implicit val stepDataListWrapperFormat =Json.format[StepDataWrapper]
And then,
val processSteps = request.body.asJson.asOpt[StepDataWrapper]
.map{
stepDataWrapper => stepDataWrapper.stepsData.map(println(_))
}
Upvotes: 3