目前正在学习 RESTFUL API 的基础知识,使用 Play,并遇到问题:我遵循一些长期教程,并认为正确的 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[Place] = List(
Place(1, "newyork"),
Place(2, "chicago"),
Place(3, "capetown")
)
def listPlaces = Action {
val json = Json.toJson(thePlaces)
Ok(json)
}
}
终于得到了答案,希望这对将来对其他人有所帮助!!
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[(Int, String)] = List(
(1, "newyork"),
(2, "chicago"),
(3, "capetown")
)
implicit val thePlacesWrites = Json.writes[PlacesController]
def listPlaces = Action {
val json = Json.toJson(thePlaces)
Ok(json)
}
}