【问题标题】:Return a Scala value as a Json string将 Scala 值作为 Json 字符串返回
【发布时间】:2021-10-23 09:59:51
【问题描述】:

在 Play Framework 中,我在控制器中有以下方法:

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 字符串返回以在我的本地主机上查看它,以响应 Ajax 请求?

【问题讨论】:

  • 这是一个 Play 应用程序吗?
  • 您阅读过 Play 框架文档吗?有一个专门的部分介绍如何使用 Play JSON 库编写 JSON...
  • 请看here

标签: json scala playframework


【解决方案1】:

不清楚这些参数是什么类型,但如果是String,根据官方documentation

case class ResultCaseClass(country: String, countryPostcodeZones: String, placeholder: String)

implicit val resultWrites: Writes[ResultCaseClass] =
 ((JsPath \ “country").write[String] and
 (JsPath \ "countryPostcodeZones").write[String] and 
 (JsPath \ “placeholder").write[String] ) (unlift(ResultCaseClass.unapply))

def country(countryCode: String) = Authorized().async { implicit request =>
  val country = Country.find(countryCode).get

  val countryPostcodeZones = postcodeZones.get(country)

  val placeholder = countryPostcodeZones.postcodeType.placeholder  

  val result = ResultCaseClass(country, countryPostcodeZones, placeholder)

  val json = Json.toJson(result)
    
  Ok(json)
}

请注意,对于像这样的简单案例类,您还可以使用宏自动生成Writes

implicit val resultWrites: Writes[ResultCaseClass] = Json.writes[ResultCaseClass]

【讨论】:

  • 嘿,非常感谢 :) 亲爱的詹姆斯,它奏效了,我为你的答案投了票,在“15 次声望”之后将可见,非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2015-10-24
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多