Scala 处理可变对象
我在应用程序中的case类中整理可变对象时遇到困难。 我正在使用spray库,并且已经进行了必要的导入Scala 处理可变对象,scala,spray-json,Scala,Spray Json,我在应用程序中的case类中整理可变对象时遇到困难。 我正在使用spray库,并且已经进行了必要的导入 import spray.json._ import DefaultJsonProtocol._ import spray.httpx.SprayJsonSupport._ 但是当我试图为我的case类提供伴生对象时,我得到了以下错误 case class CasePage(pageId:String,userList:ListBuffer[String],c
import spray.json._
import DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport._
但是当我试图为我的case类提供伴生对象时,我得到了以下错误
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]]
没有可变对象的其他case类工作正常。只是scala.collection.mutable类对象有问题。我错过了什么
谢谢您需要一个
RootJsonFormat
实例,用于ListBuffer
。但请注意,在case类中使用collection.mutable
并不是惯用的Scala
package.com.example
导入spray.json_
导入DefaultJsonProtocol_
导入scala.collection.mutable.ListBuffer
对象SO33943345{
案例类案例页面(pageId:String,
userList:ListBuffer[String],
commentList:ListBuffer[String],
picList:ListBuffer[字符串],
likeList:ListBuffer[字符串])
隐式定义listBufferFormat[T:JsonFormat]=新根JsonFormat[ListBuffer[T]]{
def write(listBuffer:listBuffer[T])=JsArray(listBuffer.map(u.toJson.toVector)
def read(值:JsValue):ListBuffer[T]=值匹配{
case JsArray(elements)=>elements.map(u.convertTo[T])(collection.breakOut)
案例x=>反序列化错误(“预期ListBuffer为JsArray,但得到”+x)
}
}
对象CasePage扩展了DefaultJsonProtocol{
隐式val inpuser=jsonFormat5(CasePage.apply)
}
def main(参数:数组[字符串]):单位={
val cp=CasePage(“1”,
ListBuffer(“用户1”、“用户2”),
ListBuffer(“Comment1”、“Comment2”),
ListBuffer(“Pic1”、“Pic2”),
ListBuffer(“Like1”、“Like2”))
println(cp.toJson.prettyPrint)
}
}
这是从官方的JSON实现Scala获得的- 只要代码只使用这些,您就只需要DefaultJsonProtocol。以下是默认JSONProtocol已经处理的类型:
- 字节,短,整数,长,浮点,双精度,字符,单位,布尔值
- 字符串,符号
- BigInt,BigDecimal
- 选项,Tuple1-Tuple7
- 列表、数组
- 不可变。{Map,Iterable,Seq,IndexedSeq,LinearSeq,Set,Vector}
- 集合。{Iterable,Seq,IndexedSeq,LinearSeq,Set}
- JsValue
完美!谢谢。我能问你为什么说使用可变对象是不可取的吗?