jfu
jfu

Reputation: 1700

Add a field while serializing an object

I have a case class

case class Foo(bar: Int, baz: String)

and I am trying to write a JSON serialization for it. But I have an additional requirement, to add one more field to the generated Json (say "greeting": "Hello")

I am trying something along these lines:

val writes = ((JsPath \ "bar").write[Int] and
   (JsPath \ "baz").write[String] and
   (JsPath \ "greeting").write[String])(unlift(Foo.unapply))

But, how should I pass the static "Hello" string to the above Writes?

And how can I use this writes to create a Format for my Foo class?

Upvotes: 0

Views: 35

Answers (3)

Michael Zajac
Michael Zajac

Reputation: 55569

In a one-off scenario, where you don't want to define yet another Writes, you could do this:

Json.toJson(foo).as[JsObject] ++ Json.obj("greeting" -> "hello")

Upvotes: 1

jfu
jfu

Reputation: 1700

I have ended up with another solution:

val writes = ((JsPath \ "bar").write[Int] and
  (JsPath \ "baz").write[String] and
  (JsPath \ "greeting").write[String])((f: Foo) => (f.bar, f.baz, "Hello"))

Upvotes: 0

tehlexx
tehlexx

Reputation: 2859

I would do it like this:

val writes = Writes[Foo](f => {
  Json.obj(
    "bar" -> f.bar,
    "baz" -> f.baz,
    "greeting" -> "Hello")
})

Drawback is that you have to specify the members twice, but it's handy for special cases like this where you need additional control.

Upvotes: 1

Related Questions