Otavio Macedo
Otavio Macedo

Reputation: 1572

JSON conditional writes in Scala

Using Play! 2.1 Json library, is there a way to write a field to json only if a certain condition is met? For example:

case class Foo(id: Int, name: String)

I'd like to define a Writes that only generates a name field if name is not empty. So that:

Json.toJson(Foo(1, "Chuck")) //yields {"id":1,"name":"Chuck"}    
Json.toJson(Foo(1, ""))      //yields {"id":1}

Upvotes: 1

Views: 456

Answers (1)

pedrofurla
pedrofurla

Reputation: 12783

You will have to write your own Writes[T] class, in this case Writes[Foo] see Scaladoc for reference. Or you can change the String to an Option[String] and write one Writes[Option[String]] or Writes[Option[_]].

I haven't tried it myself but it's very similar to Spray-json which I have used in the past.

Upvotes: 4

Related Questions