0

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.

                 ^**
1
  • First of all you have to run the query as mentioned in Anorm docs. Then you will have a type which should be serializable to json (you need a Reads or Format of that type). By the way, reading Play docs concerning JSON is highly recommended. Commented Mar 14, 2015 at 13:37

1 Answer 1

1

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))
  }
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.