Assigning default value to optional parameter in service (JSON)

Hello,

I’m just starting with Lagom (and Scala) and I created a service to add books and persist them. One thing that I couldnt find is how you can make JSON parameters optional but still assign a default value to it?

I have a service to Post a Book:
namedCall("/api/postBooks", postBooks _)

Which maps on:
def postBooks(): ServiceCall[List[Book], Done]

To make a JSON parameter optional so that it does not throw an error when it is not provided in the JSON, I am using the Option[] parameter which also works:

case class Book(titleName: String, publishingDate: Option[Int] = Some(0))

(I limited to two parameters here to make it more readable)

I would have assumed that adding “= Some(0)” would add a default parameter when there is no publishingDate in the JSON sent to my service, but this is not the case. When publishingDate is not added, it will not have a value in my Book object.

Any idea how I can add a default value when it was not provided by the User in the JSON?

Thanks!

I found a similar question on StackOverflow:

n Play 2.6 you can write simply:

Json.using[Json.WithDefaultValues].reads[Test]

In your case:

implicit val bookReads = Json.using[Json.WithDefaultValues].reads[Book]

This seems to be missing from the documentation. I added a note to the issue for this feature:

A contribution from the community to the documentation would be very welcome!

1 Like

Thank you. I’ve got this working.

@Others who have no experience with Play like me and dont immediately know how to apply this Reads object.

I replaced:

implicit val format: Format[Book] = Json.format[Book]

By

  implicit val format: Format[Book] = Format[Book](
    Json.using[Json.WithDefaultValues].reads[Book],
    Json.writes[Book]
  )

Im not sure if this is the way to do it, but is is working :slightly_smiling_face:

Glad you got it working. This will also work and is a little shorter:

implicit val format: Format[Book] = Json.using[Json.WithDefaultValues].format[Book]