I am trying Scala with Play framework and coming from 10+ years of Java/Spring experience
Below is the source code I am trying
Routes file
GET /stock controllers.HomeController.saveStock
Sample Model object
import play.api.libs.json._
case class Stock(symbol: String = "", price: Double = 0d)
object Stock {
implicit def stockReads = Json.reads[Stock]
implicit def stockWrites = Json.writes[Stock]
implicit def stockFormat = Json.format[Stock]
}
Sample Controller
import models.Stock
import javax.inject._
import play.api.mvc._
import play.api.libs.json._
@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc: ControllerComponents) {
def index() = Action { implicit request: Request[AnyContent] =>
Ok(views.html.index())
}
def saveStock = Action{ implicit request: Request[AnyContent] =>
var stocks = List(Stock())
println(stocks)
Ok(Json.toJson(Stock)).as("application/json")
//Ok
}
}
build.sbt
scalaVersion := "2.13.6"
libraryDependencies += guice
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "5.0.0" % Test
libraryDependencies += "com.typesafe.play" %% "play-server" % "2.8.8"
libraryDependencies += "com.typesafe.play" %% "play-slick" % "5.0.0"
libraryDependencies += "com.github.tminglei" %% "slick-pg" % "0.19.7"
libraryDependencies += "ai.x" %% "play-json-extensions" % "0.42.0"
Error - http://localhost:9000/ No Json serializer found for type models.Stock.type. Try to implement an implicit Writes or Format for this type.
In the error message "No Json serializer found for type models.Stock.type
", one important thing to notice is the .type
suffix.
It's referring to the object Stock
, not the case class
. That is the error is saying "I don't know how to serialize object Stock
".
This is because you wrote Json.toJson(Stock)
instead of Json.toJson(Stock())
or maybe you meant Json.toJson(stocks)
.
Stock
refers to the object
while Stock()
is Instantiating the case class
.
Also:
as(...)
if using a JsObject
in the result.Reads
nor a Writes
if you provide a Format
(the later is providing the 2 former)val
rather than var
(immutability is the strength of Scala)