spray / spray-json

A lightweight, clean and simple JSON implementation in Scala
Apache License 2.0
969 stars 190 forks source link

Default JsonWriter for collections #337

Open pocorall opened 3 years ago

pocorall commented 3 years ago

Thank you for making this amazing project.

I am using this for serializing my classes, so I defined a JsonWriter. By default, spray-json does not provide JsonWriter for Seq:

import spray.json._

case class A(num: Int)

implicit val aWriter = new JsonWriter[A] {
  override def write(a: A): JsValue = JsObject("myNum" -> JsNumber(a.num))
}

val a = A(32)
a.toJson // OK
val seqA: Seq[A] = Seq(A(11), A(55))
seqA.toJson // Not possible

I wrote it for my case, but it would be much better if this project includes this.

def viaSeq[I <: Iterable[T], T :JsonWriter](f: Seq[T] => I): RootJsonWriter[I] = new RootJsonWriter[I] {
  def write(iterable: I) = JsArray(iterable.iterator.map(_.toJson).toVector)
}
implicit def seqWriter[T: JsonWriter] = viaSeq[Seq[T], T](seq => Seq(seq :_*))

seqA.toJson // now this works