Search code examples
jsonscalaplayframeworkfunctional-programmingcombinators

Write an Arbitrary Value Not Found in a Case Class Using Play's (2.2) Scala JSON Combinators


I'd like to implement a Writes that emits a JSON object that's not found in the class being serialized.

For case class:

case class Foo(i:Int, s:String)

I'm looking to produce:

{
  "i": <int>,
  "s": "<string>",
  "other": "Some value."
}

The naïve first attempt was:

val writes: Writes[Foo] = ((
  (__ \ "i").write[Int] and
    (__ \ "s").write[String] and
    (__ \ "other").write("Some value.")
  )(unlift(Foo.unapply))

Naturally, that won't compile as the subsequent and calls produce a CanBuild3 and Foo's unapply produces a Tuple2. I'd looked into appending a value to the result, producing a Tuple3, but what I've found looks pretty bad and the language maintainers will not implement it.

There are ways to work-around this, but I'd rather not pollute my model classes with these decorator values I'd like added to the resulting JSON.

Any suggestions?

It's worth noting you can go the other direction, providing values with Reads.pure for cases where a value does not exist in JSON but is specified by the resulting object.


Solution

  • You can do this pretty straightforwardly by desugaring a bit:

    val writes: Writes[Foo] = (
      (__ \ "i").write[Int] and
      (__ \ "s").write[String] and
      (__ \ "other").write[String]
    )(foo => (foo.i, foo.s, "Some value."))
    

    The unlift(Foo.unapply) is just a fancy way to get a function from a Foo to a tuple of the kind required by the preceding applicative builder expression, and you can replace it with your own function that can add whatever you want.

    If you really wanted even cleaner syntax, you could use Shapeless:

    import shapeless.syntax.std.tuple._
    
    val writes: Writes[Foo] = (
      (__ \ "i").write[Int] and
      (__ \ "s").write[String] and
      (__ \ "other").write[String]
    )(_ :+ "Some value.")
    

    It's beautiful, but may be overkill.