I'm trying to include more than one item in my json object (currently I can only add one item),
In my scala class I have:
case class Api(row:Int,name:String,age:Int)
Ok(Json.obj("status" -> "ok", "cars" -> carsBooked.map(_.row), "saved" -> saved, "failed" -> failed, "notBooked" -> Response.errors))
<<---- this works perfectly and I'm able to get a list of all the row in json, but how do i add name and age?
Ideally I wanna do something like carsBooked.map(_.row._name etc..)
Thanks!
If we have
case class Api(row: Int, name: String, age: Int)
then we can generate codecs automatically .
object Api {
implicit val apiReads: Reads[Api] = Json.reads[Api]
implicit val apiWrites: OWrites[Api] = Writes.writes[Api]
}
and then we could write:
Ok(Json.obj("status" -> "ok", "cars" -> Json.toJson(carsBooked), "saved" -> saved, "failed" -> failed, "notBooked" -> Response.errors))
or we can actually make this also automated:
case class ApiResult(
status: String,
cars: List[Api],
saved: List[String],
failed: List[String],
notSaved: List[String]
)
object ApiResult {
implicit val apiResultReads: Reads[ApiResult] = Json.reads[ApiResult]
implicit val apiResultWrites: OWrites[ApiResult] = Writes.writes[ApiResult]
}
val apiResult: ApiResult = ...
Ok(Json.toJson(apiResult))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.