Reputation: 13
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
Upvotes: 1
Views: 776
Reputation: 11
Got this from the official JSON implementation is Scala https://github.com/spray/spray-json - As long as your code uses nothing more than these you only need the DefaultJsonProtocol. Here are the types already taken care of by the DefaultJsonProtocol:
@racetrack's implementation works, however, you need to understand that the mutable state is often associated with poor performance due to side effects and less predictability. Scala advocates for functional programming (or in other words, programming devoid side effects and immutable structures). It however provides classes/collections for the imperative paradigm but this isn't the default.
Upvotes: 0
Reputation: 3756
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)
}
}
Upvotes: 1