当前正在通过Play学习RESTFUL API的基础知识,并且遇到了问题:正在学习一些长期的教程,并认为使用正确的scala语法会失败!需要帮助,谢谢
package controllers
import play.api.libs.json.Json
import javax.inject.Inject
import play.api.Configuration
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.ExecutionContext
class PlacesController @Inject()(cc: ControllerComponents)(implicit assetsFinder: AssetsFinder, ec: ExecutionContext, configuration: Configuration)
extends AbstractController(cc) {
case class PlacesController(id: Int, name: String)
val thePlaces: List = List(
thePlaces(1, "newyork"),
thePlaces(2, "chicago"),
thePlaces(3, "capetown")
)
implicit val thePlacesWrites = Json.writes[PlacesController]
def listPlaces = Action {
val json = Json.toJson(thePlaces)
Ok(json)
}}
您的代码有很多问题。您正在定义thePlaces
,同时在定义的右侧调用thePlaces
本身。
而且,您的命名令人困惑。
尝试一下:
final case class Place(id: Int, name: String)
object Place {
implicit val placeWrites = Json.writes[Place]
}
class PlacesController ... {
val thePlaces: List = List(
Place(1, "newyork"),
Place(2, "chicago"),
Place(3, "capetown")
)
def listPlaces = Action {
val json = Json.toJson(thePlaces)
Ok(json)
}
}