Play Framework中如何将Scala值作为JSON字符串响应Ajax请求
Play Framework 控制器返回JSON响应实现方案
1. 定义JSON序列化隐式规则
Play 框架内置的JSON模块需要通过Writes隐式值来实现Scala对象到JSON的序列化,你需要给所有要序列化为JSON的自定义类添加对应规则:
import play.api.libs.json._ // 示例:给你的业务类添加Writes隐式值,可直接用Json.writes宏自动生成 case class Country(code: String, name: String) object Country { implicit val countryWrites: Writes[Country] = Json.writes[Country] } case class PostcodeType(placeholder: String) object PostcodeType { implicit val postcodeTypeWrites: Writes[PostcodeType] = Json.writes[PostcodeType] } case class CountryPostcodeZones(postcodeType: PostcodeType) object CountryPostcodeZones { implicit val zonesWrites: Writes[CountryPostcodeZones] = Json.writes[CountryPostcodeZones] }
2. 修改控制器方法构造JSON返回值
在你原有方法的末尾,组装需要返回的字段,封装为Ok响应返回即可,async方法要求返回Future[Result]类型:
import play.api.mvc._ import play.api.libs.json._ import scala.concurrent.Future def country(countryCode: String) = Authorized().async { implicit request => val country = Country.find(countryCode).get val countryPostcodeZones = postcodeZones.get(country) val placeholder = countryPostcodeZones.postcodeType.placeholder // 按需组装返回的JSON结构,也可以直接序列化单个对象 val respJson = Json.obj( "country" -> country, "postcodePlaceholder" -> placeholder, "postcodeZones" -> countryPostcodeZones ) Future.successful(Ok(respJson)) }
3. 配置路由
在conf/routes文件中添加对应接口的路由规则,替换为你实际的控制器名称:
GET /api/country/:countryCode controllers.XXController.country(countryCode)
4. 本地测试与跨域处理
- 启动Play本地服务后,直接访问
http://localhost:9000/api/country/对应国家编码即可看到返回的JSON结构,前端发Ajax请求时会自动识别application/json类型的响应。
若前端本地服务与Play服务端口不同存在跨域问题,可在
conf/application.conf中添加CORS配置:play.filters.cors { allowedOrigins = ["http://localhost:你前端的服务端口"] allowedHttpMethods = ["GET", "POST", "OPTIONS"] allowedHttpHeaders = ["*"] }同时需要将CORS过滤器加入到项目的全局过滤器配置中即可正常请求。
内容的提问来源于stack exchange,提问作者Gunner
相关产品推荐
相关产品推荐

