我有这个结构
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)将其移动到json时// attach是创建的Attachment对象我得到错误:
AttachmentPayload.scala:18:找不到unapply或unapplySeq函数 [error]隐式val attachmentPayloadWrites = Json.writes [AttachmentPayload]
我迷失了如何创建unapply方法。
答案 0 :(得分: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
}
}
当然,案例类方法更简单,所以我建议您使用它而不是手动创建apply / unapply方法。