【问题标题】:Scala somewhat Complex class structure to Json ObjectScala对Json Object有点复杂的类结构
【发布时间】:2017-08-15 19:42:16
【问题描述】:

我有这个结构

case class Attachment( Type: String = "template", var payload: AttachmentPayload){

}


object Attachment {
  implicit val attachmentWrites = Json.writes[Attachment]
}


object AttachmentPayload {

  implicit val attachmentPayloadWrites = Json.writes[AttachmentPayload]

}


class AttachmentPayload(val templateType: String, val elements: Option[ListBuffer[Element]] = None){

}

case class Element(title: String, imageUrl:String, subTitle: String, defaultAction: DefaultAction, buttons: Seq[Button]) {

}

当我尝试使用 Json.toJson(attach) //attach 将其移动到 json 是创建的附件对象时,我收到错误:

AttachmentPayload.scala:18: 未找到 unapply 或 unapplySeq 函数 [错误] 隐式 val attachmentPayloadWrites = Json.writes[AttachmentPayload]

我不知道如何创建 unapply 方法。

【问题讨论】:

    标签: json scala playframework


    【解决方案1】:

    您的AttachmentPayload 不是案例类。您必须将其设为案例类:

    case class AttachmentPayload(templateType: String, elements: Option[ListBuffer[Element]] = None)
    

    或者在伴随对象中手动创建apply/unapplyMethods:

    object AttachmentPayload {
      def apply(templateType: String, elements: Option[ListBuffer[Element]] = None): AttachmentPayload = new AttachmentPayload(templateType, elements)
    
      def unapply(value: Any): Option[(String, Option[ListBuffer[Element]])] = value match {
        case a: AttachmentPayload => Some((a.templateType, a.elements))
        case _ => None
      }
    }
    

    当然,案例类方法更简单,所以我建议您使用它而不是手动创建应用/取消应用方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多