Playframework 2.4.x Json 写 List[(String, String)]

Posted

技术标签:

【中文标题】Playframework 2.4.x Json 写 List[(String, String)]【英文标题】:Playframework 2.4.x Json write List[(String, String)] 【发布时间】:2016-02-17 13:45:17 【问题描述】:

我正在尝试更新一些代码。我在尝试编写 json 隐式编写器时遇到此案例类的问题

case class TemplateEmailMessage(recipients: List[EmailRecipient], globalEmailVars: List[(String, String)])

原来是这样

implicit val templateEmailMessageWrites = new Writes[TemplateEmailMessage] 
        def writes(m: TemplateEmailMessage): JsValue = 
            val globalVars: List[JsValue] = m.globalEmailVars.map(g => Json.obj("name" -> g._1, "content" ->g._2))
            Json.obj(
        "to" -> m.recipients,
        "global_merge_vars" -> JsArray(globalVars)
            )
        
    

现在是这样的。显然不起作用,因为第二个字段的类型 List[(String, String)]

object TemplateEmailMessage 

  implicit val templateEmailMessageWrites: Writes[TemplateEmailMessage] = (
    (JsPath \ "to").write[List[EmailRecipient]] and
    (JsPath \ "global_merge_vars").write[List[(String, String)]]
  )(unlift(TemplateEmailMessage.unapply))


我不知道如何翻译 JsArray,因为之前它被用来操作 writer 中的值。我应该像旧方式一样离开还是有其他方式?

谢谢

【问题讨论】:

【参考方案1】:

你可以这样做:

object TemplateEmailMessage
implicit val templateEmailMessageWrites: Writes[TemplateEmailMessage] = (
  (JsPath \ "to").write[List[EmailRecipient]] and
  (JsPath \ "global_merge_vars").write[JsArray]
     .contramap[List[(String, String)]](list => JsArray(list.map(g => Json.obj("name" -> g._1, "content" ->g._2))))
 )(unlift(TemplateEmailMessage.unapply))

其他选项,是将 (String, String) 元组转换为案例类并为其创建编写器。

case class Variable(name: String, content: String)
object Variable
implicit val variableWrites: Writes[Variable] = (
  (JsPath \ "name").write[String] and
  (JsPath \ "content").write[String]
 )(unlift(Variable.unapply))

然后:

implicit val templateEmailMessageWrites: Writes[TemplateEmailMessage] = (
  (JsPath \ "to").write[List[EmailRecipient]] and
  (JsPath \ "global_merge_vars").write[List[Variable]]
)(unlift(TemplateEmailMessage.unapply))

【讨论】:

以上是关于Playframework 2.4.x Json 写 List[(String, String)]的主要内容,如果未能解决你的问题,请参考以下文章

Play Framework 2.4.x - 覆盖默认的 Actor 系统创建

Play Framework [2.4.x] 如何在子模块的路由文件中处理公共资产

Play Framework 2.4.x 自定义部署脚本

手动调用 PlayFramework 自定义错误页面

Play Framework [2.4.x] - 模块路由特定名称因“资产不是包的成员”而失败

playframework - 修剪 json 值的最佳方法