I am new to Scala and play 2 and haven't found a way to return a Json request from the database using Anorm. This is my simple code
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val readLocations = SQL("select city,state from zips limit 1")
Ok(Json.toJson(readLocations))
}
The method is a post I simply want to return via Json 1 record from the database table there but I get this error Error:(57, 21) Play 2 Compiler: .scala:57: No Json serializer found for type anorm.SqlQuery. Try to implement an implicit Writes or Format for this type. Ok(Json.toJson(readLocations))
Any suggestions would be welcomed, I have been switching the code above some but nothing is working. I know I need to do a Write or Format but can't seem to find out how.
^**
Looks like you are trying to send a List of Locations. You could do:
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val locationFmt = Json.format[Location]
case class Location(city: String, state: String)
//Send Multiple Locations if you want
val readLocations = SQL("select city,state from zips").list.map{case Row(city: String, state: String) =>
Location(city, state)
}
// Send a single Location
val readLocation = SQL("select city,state from zips limit 1").list.headOption.map{case Row(city: String, state: String) =>
Location(city, state)
}.getOrElse(throw new NoSuchElementException)
Ok(Json.toJson(readLocation))
}
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.