Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default JsonWriter for collections #337

Open
pocorall opened this issue Mar 17, 2021 · 0 comments
Open

Default JsonWriter for collections #337

pocorall opened this issue Mar 17, 2021 · 0 comments

Comments

@pocorall
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant