Skip to content

Default JsonWriter for collections #337

@pocorall

Description

@pocorall

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions