Fernando André
Fernando André

Reputation: 1213

Scala somewhat Complex class structure to Json Object

I have this structure

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]) {

}

When I try to move this to json using Json.toJson(attach) //attach is the Attachment object created I get the error:

AttachmentPayload.scala:18: No unapply or unapplySeq function found [error] implicit val attachmentPayloadWrites = Json.writes[AttachmentPayload]

I'm lost on how to create the unapply method.

Upvotes: 0

Views: 121

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 127851

Your AttachmentPayload is not a case class. You have either to make it a case class:

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

or to create the apply/unapplyMethods in the companion object manually:

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
  }
}

Naturally, the case class approach is simpler, so I suggest you to go with it instead of creating apply/unapply methods manually.

Upvotes: 1

Related Questions