scalaspray-json

Spray Json Marshalling Mutable Objects


I'm having difficulty marshalling mutable objects in my case classes in my Application. I'm using the spray libraries and I have made the necessary imports

    import spray.json._
    import DefaultJsonProtocol._
    import spray.httpx.SprayJsonSupport._

But I get the following error when I try to provide the companion object for my case class.

    case class CasePage(pageId:String,userList:ListBuffer[String],commentList:ListBuffer[String],picList:ListBuffer[String],likeList:ListBuffer[String])

    object CasePage extends DefaultJsonProtocol {
            implicit val impUser = jsonFormat5(CasePage.apply)
            }

    could not find implicit value for evidence parameter of type CasePage.JF[scala.collection.mutable.ListBuffer[String]]

The other case classes without the mutable objects work fine. Just having trouble with scala.collection.mutable class objects. What am I missing?

Thank you


Solution

  • You need a RootJsonFormat instance for ListBuffer. But note that using collection.mutable in case classes is not idiomatic Scala.

    package com.example
    
    import spray.json._
    import DefaultJsonProtocol._
    
    import scala.collection.mutable.ListBuffer
    
    object SO33943345 {
      case class CasePage(pageId: String,
        userList: ListBuffer[String],
        commentList: ListBuffer[String],
        picList: ListBuffer[String],
        likeList: ListBuffer[String])
    
      implicit def listBufferFormat[T :JsonFormat] = new RootJsonFormat[ListBuffer[T]] {
        def write(listBuffer: ListBuffer[T]) = JsArray(listBuffer.map(_.toJson).toVector)
        def read(value: JsValue): ListBuffer[T] = value match {
          case JsArray(elements) => elements.map(_.convertTo[T])(collection.breakOut)
          case x => deserializationError("Expected ListBuffer as JsArray, but got " + x)
        }
      }
    
      object CasePage extends DefaultJsonProtocol {
        implicit val impUser = jsonFormat5(CasePage.apply)
      }
    
      def main(args: Array[String]): Unit = {
        val cp = CasePage("1",
          ListBuffer("User1", "User2"),
          ListBuffer("Comment1", "Comment2"),
          ListBuffer("Pic1", "Pic2"),
          ListBuffer("Like1", "Like2"))
    
        println(cp.toJson.prettyPrint)
      }
    }