Custom Json Writes with combinators - not all the fields of the case class are needed

Viewed 4794

I'm trying to write a custom Json serializer in play for a case class but I don't want it to serialize all the fields of the class. I'm pretty new to Scala, so that is surely the problem but this is what I tried so far:

case class Foo(a: String, b: Int, c: Double)

Now the default way of doing this, as far as I saw in the examples is:

implicit val fooWrites: Writes[Foo] = (
  (__ \ "a").write[String] and
  (__ \ "b").write[Int]
  (__ \ "c").write[Double]
) (unlift(Foo.unapply))

But what if I want to omit "c" from the Json output? I've tried this so far but it doesn't compile:

implicit val fooWritesAlt: Writes[Foo] = (
  (__ \ "a").write[String] and
  (__ \ "b").write[Int]
) (unlift({(f: Foo) => Some((f.a, f.b))}))

Any help is greatly appreciated!

5 Answers

If you are using Playframework 2.2 (not sure about earlier versions, but it should work as well) try this:

implicit val writer = new Writes[Foo] {
  def writes(foo: Foo): JsValue = {
    Json.obj("a" -> foo.a,
             "b" -> foo.b)
  }
}

What version of Play are you using? fooWritesAlt compiles for me using 2.1.3. One thing to note is that I needed to explicitly use the writes object to write the partial JSON object, i.e.

fooWritesAt.writes(Foo("a", 1, 2.0))

returns

{"a": "a", "b": 2}
Related