将有点复杂的类结构Scala到Json对象
我有这个结构将有点复杂的类结构Scala到Json对象,json,scala,playframework,Json,Scala,Playframework,我有这个结构 case class Attachment( Type: String = "template", var payload: AttachmentPayload){ } object Attachment { implicit val attachmentWrites = Json.writes[Attachment] } object AttachmentPayload { implicit val attachmentPayloadWrites = Json
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将其移动到json时。toJsonattach//attach是创建的附件对象,我得到错误:
AttachmentPayload.scala:18:未找到unapply或unapplySeq函数
[错误]隐式val attachmentPayloadWrites=
Json.writes[AttachmentPayload]
我不知道如何创建unapply方法。您的AttachmentPayload不是case类。您必须使其成为案例类:
case class AttachmentPayload(templateType: String, elements: Option[ListBuffer[Element]] = None)
或手动在伴生对象中创建应用/取消应用方法:
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
}
}
当然,case类方法更简单,因此我建议您使用它,而不是手动创建apply/unapply方法